Angular @ViewChild(ElementRef.nativeElement)返回未定义的
我有一个父组件,它通过Angular @ViewChild(ElementRef.nativeElement)返回未定义的,angular,typescript,Angular,Typescript,我有一个父组件,它通过*ngFor打印子组件 <app-item *ngFor="let item of items; let i = index" [item]="item" [index]="i" (edited)="updateItems($event)"> </app-item> 子组件具有以下模板 <input [(ngModel)]="item" #input type="text" class="form-control" (blur)=
*ngFor
打印子组件
<app-item
*ngFor="let item of items; let i = index"
[item]="item" [index]="i" (edited)="updateItems($event)">
</app-item>
子组件具有以下模板
<input [(ngModel)]="item" #input type="text" class="form-control" (blur)="editEnd()">
下一节课呢
export class ItemComponent implements OnInit {
@Output()
edited = new EventEmitter<{index: number, value: string}>();
@ViewChild('input', {read: ElementRef}) input: ElementRef;
isEditing = false;
@Input() item: string;
@Input() index: number;
constructor() { }
ngOnInit() {
}
editStart(): void {
this.isEditing = true;
console.log(this.input);
}
editEnd(): void {
this.isEditing = false;
this.edited.emit(
{
index: this.index,
value: this.item
}
);
console.log('ended');
}
delete(): void {
console.log('deleted');
}
}
导出类ItemComponent实现OnInit{
@输出()
编辑=新的EventEmitter();
@ViewChild('input',{read:ElementRef})input:ElementRef;
i编辑=假;
@Input()项:字符串;
@Input()索引:数字;
构造函数(){}
恩戈尼尼特(){
}
editStart():void{
this.isEditing=true;
console.log(this.input);
}
editEnd():void{
this.isEditing=false;
这是我编辑的(
{
索引:这个,
值:this.item
}
);
console.log('end');
}
delete():void{
console.log('deleted');
}
}
问题是
console.log(this.input.nativeElement)
返回未定义的console.log(this.input)代码>包含属性“nativeElement”。我试图将ViewChild更改为ViewChildren,但仍然console.log(this.input.nativeElement.first())代码>返回未定义的。是否可能重复您将console.log放在何处?不应使用ngOnIniton函数editStart
,该函数会触发ngIf的状态更改