tes*_*ing 19 javascript typescript angular
从官方文档.答ViewChild:
Configures a view query.
View queries are set before the ngAfterViewInit callback is called.
Run Code Online (Sandbox Code Playgroud)
解释是非常小的,我仍然不太明白它用于什么.
从我发现的博客中考虑这个例子.
带走对@ViewChild(TodoInputCmp)内部代码没有影响TodoInputCmp
有人可以给我一些见解吗?
谢谢
Gün*_*uer 24
它提供了视图中元素或组件的引用:
@Component({
...
directives: [SomeComponent],
template: `
<div><span #myVar>xxx</span><div>
<some-comp></some-comp>`
})
class MyComponent {
@ViewChild('myVar') myVar:ElementRef;
@ViewChild(SomeComponent) someComponent:SomeComponent;
ngAfterViewInit() {
console.log(this.myVar.nativeElement.innerHTML);
console.log(this.someComponent);
}
}
Run Code Online (Sandbox Code Playgroud)
之前没有初始化变量 ngAfterViewInit()
@viewchild()在Angular中,我们通过将普通HTML与其他Angular组件结合来定义组件的模板。在视图(html文件)中,我们可以通过以下方式定义模板引用变量:
<input type="text" #firstNameInput>
<myDefaultComponent #reference></myDefaultComponent>
Run Code Online (Sandbox Code Playgroud)
使用模板引用变量,组件和html元素通常仅在视图内部可用。但是,当我们想注入组件或html元素的引用并将它们注入到我们的模型(ts文件组件类)中时,可以使用@viewchild()它来实现此目的。
我们通过@viewchild()以下方式使用装饰器:
@ViewChild('myReference') myClassproperty;
Run Code Online (Sandbox Code Playgroud)
@viewchild()根据引用的放置位置,using 将执行不同的操作:
this.myClasspropertythis.myClassproperty因此@viewchild(),将其他子组件或HTML子元素注入模型类非常方便。现在,父组件可以根据其子组件和html元素的行为做出反应,这是经常需要的功能。
警告:
另外需要注意的重要的是,你应该把@viewchild()在一个ngAfterViewInit()钩。这是因为渲染后只能访问视图中的元素。
| 归档时间: |
|
| 查看次数: |
9214 次 |
| 最近记录: |