如何将 elementref 选择器从对象绑定到 Angular 中的 html

问题描述 投票:0回答:1

我想以角度将对象中的 elementref 绑定到我的 html。我尝试的是:

<div #[sec_variable] ></div> OR <div #sec_variable ></div>

并从 @ViewChild() 获取它,但它说它为空。

<div class="nav-item" *ngFor="let input of inputs">
  <div #[input.name] /></div>
</div>

并且

 @ViewChild('image',{static:true,read:ElementRef}) img?

 ngOnInit(): void {

  const label = this.renderer.createElement('label');
  this.renderer.setAttribute(label, 'for', 'image');
  this.renderer.appendChild(this.img.nativeElement, label)
 }

但是它不起作用。我怎样才能动态地使用它

javascript angular typescript dynamic binding
1个回答
0
投票

有点像

@ViewChild('inputEmail') inputEmail!: ElementRef<HTMLInputElement>; 

<input #inputEmail>

顺便说一句,在您的情况下, static 是不正确的,因为您正在查询的元素是由 ngFor 指令动态创建的。

© www.soinside.com 2019 - 2024. All rights reserved.