返回

Angular 装饰器之 @ViewChild | 深入理解元素引用

前端

@ViewChild装饰器

Angular 装饰器 @ViewChild 用于在模板中查询一个子组件,并将该子组件的实例注入到当前组件中。这对于需要访问子组件元素、获取元素属性或调用元素方法的情况非常有用。

基本用法

@ViewChild装饰器的基本用法如下:

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;
}

在这个例子中,@ViewChild装饰器被用于查询名为child的子组件。然后,子组件的实例会被注入到ParentComponent中,并可以通过this.child来访问。

访问子组件元素

使用@ViewChild装饰器,可以轻松地访问子组件的元素。例如,以下代码演示了如何访问子组件的input元素:

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;

  ngAfterViewInit() {
    console.log(this.child.inputElement.value);
  }
}

获取子组件属性

@ViewChild装饰器还可以用于获取子组件的属性。例如,以下代码演示了如何获取子组件的name属性:

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;

  ngAfterViewInit() {
    console.log(this.child.name);
  }
}

调用子组件方法

@ViewChild装饰器还可以用于调用子组件的方法。例如,以下代码演示了如何调用子组件的sayHello方法:

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;

  ngAfterViewInit() {
    this.child.sayHello();
  }
}

@ViewChildren装饰器

@ViewChildren装饰器类似于@ViewChild装饰器,但它可以查询多个子组件。例如,以下代码演示了如何查询所有名为child的子组件:

@Component({
  selector: 'app-parent',
  template: `<app-child *ngFor="let child of children"></app-child>`
})
export class ParentComponent {
  @ViewChildren('child') children: QueryList<ChildComponent>;

  ngAfterViewInit() {
    console.log(this.children);
  }
}

组件通信

@ViewChild和@ViewChildren装饰器可以用于在组件之间进行通信。例如,以下代码演示了如何从父组件向子组件发送消息:

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;

  sendMessage() {
    this.child.message = 'Hello from parent!';
  }
}

@Component({
  selector: 'app-child',
  template: `<p>{{message}}</p>`
})
export class ChildComponent {
  message: string;
}

总结

@ViewChild和@ViewChildren装饰器是Angular中非常有用的装饰器,可以用于访问子组件元素、获取元素属性、调用元素方法以及在组件之间进行通信。