zoukankan      html  css  js  c++  java
  • angular父子组件相互传值

    // 调用子组件  向子组件传值和方法的方式
    <app-header [title]="title" [run]="run" [parent]="this"></app-header>

    在子组件中,引入Input,通过@input() 方式引入,即可通过this.xxx使用

    import { Component, OnInit, Input } from '@angular/core';

    @Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
    })
    export class HeaderComponent implements OnInit {
    constructor() { }
    @Input() title: any;
    @Input() run: any;
    @Input() parent: any;
    ngOnInit() {
    }
    getPatrent() {
    this.run();
    this.parent.run(); // 可以直接调用父组件的属性和方法
    }
    }

     子组件向父组件间传值

    1、通过ViewChild获取子组件的方法和属性 

    import { Component, OnInit, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.less']
    })
    export class HomeComponent implements OnInit {
      public title: any = '首页';
      @ViewChild('child', {static: false}) child: any;
      constructor() { }
      ngOnInit() {
      }
      run() {
        alert('父组件');
      }
      getChildValue() {
        this.child.childRun(); // 通过这种方式可以获取到子组件的方法和属性值
      }
      childFun(e) {
        console.log(e);
      }
    }

    2、通过事件广播

    子组件中引入Output和EventEmitter,再使用@Output定义,通过emit分发

     父组件中接收(同vue中的emit)

  • 相关阅读:
    python 如何将md5转为16字节
    linux非root用户执行开机启动程序
    python 正则表达式的使用
    Go随机数的使用
    Go 的类型断言type assertion
    go get中的...
    Go语言圣经
    python入门第三十五天--事件驱动模型(补)练习理解
    MySQL_Ubuntu安装
    JAVA入门基础--数据类型
  • 原文地址:https://www.cnblogs.com/cazj/p/11959189.html
Copyright © 2011-2022 走看看