У меня есть страница, где есть простая форма NgForm
, я пытаюсь отключить определенное поле после загрузки страницы / представления.
Но я получаю неопределенное исключение:
ОШИБКА TypeError: Невозможно прочитать свойство 'disable' из неопределенного
код component.ts:
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'sub',
templateUrl: 'sub.component.html'
})
export class SubComponent implements OnInit, AfterViewInit {
@ViewChild('userForm') uf: NgForm;
ngOnInit() {
console.log(this.uf);
console.log(this.uf.controls['name']) // this is null
}
ngAfterViewInit() {
console.log('kasdkfj')
console.log(this.uf);
console.log(this.uf.controls['name']) // this is null
this.uf.controls['name'].disable(); // Exception here
}
onSubmit(value: any) {
console.log(this.uf.controls['name']) // But this is NOT null
this.uf.controls['name'].disable(); // NO Exception, works perfectly
console.log(value);
}
}
HTML код:
<div class="container">
<h2>Form Data</h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div><br/>
<div ngModelGroup="address">
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" name="city" ngModel>
</div><br/>
<div class="form-group">
<label>Pin</label>
<input type="text" class="form-control" name="pin" ngModel>
</div><br/>
<div class="form-group">
<label>State</label>
<input type="text" class="form-control" name="state" ngModel>
</div><br/>
</div>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
</div>
Но тот же код, когда я делаю это при любом нажатии кнопки или при отправке, работает без проблем.
Вопрос: Как отключить одно из полей после инициализации формы?
Stackblitz Link