zoukankan      html  css  js  c++  java
  • angular——组件交互

     

      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");

        }

        

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

  • 相关阅读:
    《算法导论》读书笔记--第三章函数的增长 课后题
    《利用python进行数据分析》读书笔记--第五章 pandas入门
    《利用python进行数据分析》读书笔记--第四章 numpy基础:数组和矢量计算
    《利用python进行数据分析》读书笔记--第三章 ipython使用
    《算法导论》读书笔记--第三章 函数的增长
    《利用python进行数据分析》读书笔记 --第一、二章 准备与例子
    《R语言实战》读书笔记--学习张丹日志
    《R语言实战》读书笔记 第七章--基本统计分析
    解决Mybatis-plus高版本不向后兼容的问题
    【Javascript】: for循环中定义的变量在for循环体外也有效
  • 原文地址:https://www.cnblogs.com/skylen/p/10119115.html
Copyright © 2011-2022 走看看