gpt4 book ai didi

angular - 模板引用变量作为其他组件的@Input()

转载 作者:太空狗 更新时间:2023-10-29 17:36:50 27 4
gpt4 key购买 nike

Angular v5.0.1

我在一个组件上有这个模板

<div #content>some content</div>
<some-component [content]="content"></some-component>

我想通过 @Input()content#content 变量的引用传递给 SomeComponent 但我不确定是什么类型变量是。

根据我在网上搜索到的内容,它似乎是 ElementRef 所以我做了

  @Input()
component: ElementRef;
ngOnInit() {
console.log(this.component); // this prints the html element on console
console.log(this.component.nativeElement); // this prints undefined
}

但是 this.component.nativeElementundefined

做更多的测试,看起来 this.component 实际上是 native element

做这样的事情是可行的,实际上背景颜色发生了变化(这只是为了测试目的,我对以这种方式实际改变颜色并不感兴趣)

this.component.style.backgroundColor = 'red';

虽然我按照我想要的方式完成了这项工作,但我有几个问题可以更好地理解它是如何工作的。

  1. #content 是原生元素而不是 ElementRef 吗?
  2. 这是将引用变量传递给另一个组件的有效 Angular 方式吗?

如果您认为这种方法是错误的或者是更好的方法,请提供一些有效的示例。

最佳答案

ngOnInit() 可能为时过早。ngAfterViewInit() 可能有效:

ngAfterViewInit() {
console.log(this.component); // this prints the html element on console
console.log(this.component.nativeElement); // this prints undefined
}

Is #content the native element and not the ElementRef ?

如果 #content 在普通元素上,则它是 nativeElement
如果元素托管组件或指令,您将获得组件或指令实例。

关于angular - 模板引用变量作为其他组件的@Input(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47284139/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com