Instead of injecting ElementRef and using querySelector or similar from there, a declarative way can be used instead to access elements in the view directly:<input #myname>@ViewChild('myname') input;元素ngAfterViewInit() { console.log(this.input.nativeElement.value);} > StackBlitz示例 @ViewChild()支持指令或组件类型作为参数,或模板变量的名称(字符串). @ViewChildren()也支持以逗号分隔列表的名称列表(当前不允许使用空格@ViewChildren('var1,var2,var3')). @ContentChild()和 @ ContentChildren()相同,但在轻型DOM(<ng-content>投影元素).@ViewChild() supports directive or component type as parameter, or the name (string) of a template variable.@ViewChildren() also supports a list of names as comma separated list (currently no spaces allowed @ViewChildren('var1,var2,var3')).@ContentChild() and @ContentChildren() do the same but in the light DOM (<ng-content> projected elements). 后裔 @ContentChildren()是唯一一个还可以查询后代的人@ContentChildren() is the only one that allows to also query for descendants@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField;{descendants: true}应该是默认值,但不在最终版本2.0.0中,它是认为错误该问题已在2.0.1中修复{descendants: true} should be the default but is not in 2.0.0 final and it's considered a bugThis was fixed in 2.0.1 阅读如果有组件和指令,则read参数允许指定应返回哪个实例.If there are a component and directives the read parameter allows to specify which instance should be returned.例如,动态创建的组件而不是默认的ElementRefFor example ViewContainerRef that is required by dynamically created components instead of the default ElementRef@ViewChild('myname', { read: ViewContainerRef }) target; 订阅更改即使仅在调用ngAfterViewInit()时才设置视图子级,而仅在调用ngAfterContentInit()时才设置内容子级,但如果要订阅查询结果的更改,则应在ngOnInit()中完成Even though view children are only set when ngAfterViewInit() is called and content children are only set when ngAfterContentInit() is called, if you want to subscribe to changes of the query result, it should be done in ngOnInit() https://github.com/angular/angular/issues/9689# issuecomment-229247134@ViewChildren(SomeType) viewChildren;@ContentChildren(SomeType) contentChildren;ngOnInit() { this.viewChildren.changes.subscribe(changes => console.log(changes)); this.contentChildren.changes.subscribe(changes => console.log(changes));} 直接DOM访问只能查询DOM元素,而不能查询组件或指令实例:can only query DOM elements, but not components or directive instances:export class MyComponent { constructor(private elRef:ElementRef) {} ngAfterViewInit() { var div = this.elRef.nativeElement.querySelector('div'); console.log(div); } // for transcluded content ngAfterContentInit() { var div = this.elRef.nativeElement.querySelector('div'); console.log(div); }} 获取任意投影内容请参见访问已包含的内容 这篇关于如何在组件模板中选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-11 21:57