码迷,mamicode.com
首页 > 其他好文 > 详细

angular——组件交互

时间:2018-12-14 14:52:31      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:nbsp   tor   count   ring   const   通过   sel   code   str   

 

  angular是以组件化的形式来实现,因而组件交互是极为基础且重要的,下面对其组件之间的交互方式一一介绍。

  1. 通过输入型绑定把数据从父组件传到子组件。

  child.component.ts:

   <p>{{message}}</p>

  parent.component.ts:  

  <app-child [message]="callChild"></app-child>
 

2. 通过serter接听输入属性值的变化
  

  技术分享图片


  parent.component.ts:
    <app-child [name]="name"></app-child>


  3.父组件监听子组件的事件

  child.component.ts:

  技术分享图片

  parent.component:

  <app-child [onVoted]="onVoted($event)"></app-child>

  onVoted(agreed: boolean) { console.log(agreed); }

 

  4. 父组件与子组件通过本地变量互动

  child:
    stop(){};
    start(){};
  
  parent:
    <app-child #child></app-child>
    <button (chilk)="child.start()"></button>
 
  注:用本地变量可使用在父组件模板里面来读取子组件的属性或者使用其方法;


  5. 父组件调用@ViewChild()

    4>局限性:只能在组件模板里面使用子组件的小户型或方法,但是父组件的类并不能使用;

    当父组件类需要这种访问时,可以把子组件作为 ViewChild,注入到父组件里面。

 

  parent:

  @ViewChild(CountdownTimerComponent)

  private childComponent: ChildComponent;

  start(){

    this.childComponent.start();

  }

 

  6. 父组件和子组件通过服务来通讯

  service:

    private a = new Subject<string>();

    private b = new Subject<string>();

    ac = this.a.asObservable();

    bc = this.b.asObservable();

    calla(messageA: string){

      this.a.next(messageA);

    } 

    callb(messageB: string){

      this.b.next(messageB);

    } 

 

  parent:

    @Component({

      selector: app-parent,

      providers: [Service]

    })

    nbr = 1;

    subscription: Subscription;

    constructor(private service: Service){

      this.subscription = service.ac.subscribe(message => {

        console.log(message);

      })

    }

    add() {

      this.service.callb(nbr);

    }

  

  child:

    constructor(private service: Service){

      this.subscription = service.bc.subscribe(message => {

        console.log(message);

      })

    }

    add(){

      this.service.calla("child call A");

    }

    

   这样子父组件都可通过自己类中的方法使用服务来影响到另一个组件

angular——组件交互

标签:nbsp   tor   count   ring   const   通过   sel   code   str   

原文地址:https://www.cnblogs.com/skylen/p/10119115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!