HTML:
<mat-form-field *ngSwitchCase="'edit'">
<input
#myInput
(keyup.enter)="edit()"
[formControl]="taskTitleControl"
matInput
/>
</mat-form-field>TS:
export class TaskComponent implements OnInit {
@Input() title: string;
@Input() backGroundColor: string = 'red';
currentMode: Mode = Mode.Show;
taskTitleControl: FormControl;
@ViewChild('myInput') input: MatInput;
constructor() {}
ngOnInit(): void {
this.taskTitleControl = new FormControl(this.title || '', [
Validators.required,
]);
}
edit(): void {
this.currentMode = this.currentMode === Mode.Edit ? Mode.Show : Mode.Edit;
console.log(this.input);
}
}我也尝试过这样使用引用:
@ViewChild(MatInput)输入: MatInput;
但仍然返回undefined,奇怪的是它只在第一次点击时返回undefined,在第二次点击时它起作用了。
我不知道ngSwitchCase是不是在干扰什么。
我做错了吗?
发布于 2021-01-01 08:50:31
如果你在视图初始化之前调用edit(),这将解释为什么viewChild为undefined,请确保edit()函数被调用ngAfterViewInit已被调用。
并添加static:flase选项
@ViewChild('myInput', { static: false }) input: ElementRef;https://stackoverflow.com/questions/65526365
复制相似问题