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

        }

        

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

  • 相关阅读:
    #leetcode#Missing Ranges
    Redhat Crash Utility-Ramdump
    Android Touch事件传递机制具体解释 下
    POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
    分析cocos2d-x的lua项目中的工具方法
    #測试相关#Getting “junit.framework.AssertionFailedError: Forked Java VM exited abnormally” Exception
    POJ 题目3264 Balanced Lineup(RMQ)
    在Linux下安装R语言软件
    谷歌浏览器插件-html页面js事件查看器
    Map集合
  • 原文地址:https://www.cnblogs.com/skylen/p/10119115.html
Copyright © 2020-2023  润新知