Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何使用@ViewChild获取HTML元素_Angular_Angular8 - Fatal编程技术网

Angular 如何使用@ViewChild获取HTML元素

Angular 如何使用@ViewChild获取HTML元素,angular,angular8,Angular,Angular8,有一个包含HTML的组件: <div class="filter" #filterContainer> 但当触发事件时,我得到console.log(this.el)未定义,为什么我无法访问元素#filterContainer?viewChild仅从具有模板引用变量的组件可见。(并且必须读取:ElementRef,而不是读取:ViewContainerRef) 如果组件具有父级,则需要从该父级访问组件,然后访问ViewChildren。是的,您可以使用父级的ViewChild

有一个包含HTML的组件:

<div class="filter" #filterContainer>   

但当触发事件时,我得到
console.log(this.el)
未定义,为什么我无法访问元素
#filterContainer

viewChild仅从具有模板引用变量的组件可见。(并且必须读取:ElementRef,而不是读取:ViewContainerRef)

如果组件具有父级,则需要从该父级访问组件,然后访问ViewChildren。是的,您可以使用父级的ViewChild(或使用模板引用)访问子级

e、 g.我们的孩子

@Component({
  selector: 'hello',
  template: `<h1 #filterContainer>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  @ViewChild('filterContainer',{static:false}) filterComponent
}
@组件({
选择器:“你好”,
模板:`Hello{{name}}!`,
样式:[`h1{font-family:Lato;}`]
})
导出类HelloComponent{
@Input()名称:string;
@ViewChild('filterContainer',{static:false})filterComponent
}
我们的父母

<hello #hello name="{{ name }}"></hello>
<button (click)="log(hello.filterComponent)">button</button>
<button (click)="log2()">button</button>

export class AppComponent  {
  name = 'Angular';
  @ViewChild(HelloComponent,{static:false}) hello
  //or
  //@ViewChild('hello',{static:false,read:HelloComponent}) hello

  log(element)
  {
    console.log(element.nativeElement.innerHTML)
  }
  log2()
  {
    console.log(this.hello.filterComponent)
  }
}

按钮
按钮
导出类AppComponent{
名称='角度';
@ViewChild(HelloComponent,{static:false})您好
//或
//@ViewChild('hello',{static:false,read:HelloComponent})hello
日志(元素)
{
log(element.nativeElement.innerHTML)
}
log2()
{
console.log(this.hello.filterComponent)
}
}

当你说“Angular apps中的某处”时,你的意思是它在某个子组件中吗?是的,它是子组件这是访问父组件中子组件的ViewChild的正确方法?
<hello #hello name="{{ name }}"></hello>
<button (click)="log(hello.filterComponent)">button</button>
<button (click)="log2()">button</button>

export class AppComponent  {
  name = 'Angular';
  @ViewChild(HelloComponent,{static:false}) hello
  //or
  //@ViewChild('hello',{static:false,read:HelloComponent}) hello

  log(element)
  {
    console.log(element.nativeElement.innerHTML)
  }
  log2()
  {
    console.log(this.hello.filterComponent)
  }
}