[英]angular4 viewchild not working on dom element
i want to know how to fetch the dom element from a components template : 我想知道如何从组件模板中获取dom元素:
Component 零件
export class JokeListComponent implements OnInit, AfterViewInit {
jokes: Joke[];
constructor() { }
@ViewChild('.myclass') el: ElementRef;
ngOnInit() {
this.jokes = [
new Joke('joke1', 'content1'),
new Joke('Joke2', 'content2'),
new Joke(),
];
}
ngAfterViewInit(): void {
console.log(this.el);
}
}
View 视图
<div class="card">
<div class="card-block">
<h4 class="card-title"> New Joke Form </h4>
<div class="myclass">
</div>
<div class="form-group">
<label for="jokeHeader">Joke Header</label>
<input type="text" id="jokeHeader" class="form-control" placeholder="Joke Head" #jokeHead>
</div>
<div class="form-group">
<label for="jokeContent">Joke Header</label>
<input type="text" id="jokeContent" class="form-control" placeholder="Joke Content" #jokeContent>
</div>
<button class="btn btn-primary" (click)="addJoke(jokeHead.value, jokeContent.value)"> Validate </button>
</div>
</div>
<hr>
<joke *ngFor="let joke of jokes" [joke]="joke" (deleteEvt)="deleteJoke($event)"></joke>
the problem is that this.el
is always undefined, i dont know why. 问题是
this.el
总是未定义,我不知道为什么。
PS: i'm using the last version of angular 4 PS:我正在使用角度4的最后一个版本
You cannot use the class name for the @ViewChild, you will need a local variable: 你不能使用@ViewChild的类名,你需要一个局部变量:
@Component({
template: `
<div><span #myVar>xxx</span><div>`
})
class MyComponent {
@ViewChild('myVar') myVar:ElementRef;
ngAfterViewInit() {
console.log(this.myVar.nativeElement);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.