zoukankan      html  css  js  c++  java
  • Angular 父子组件以及组件之间通讯

     

     一、 父组件给子组件传值-@input

    例如 根组件是

    home是父组件

    header是子组件

    在home.component.html引入子组件:<header

    1. 父组件调用子组件的时候传入数据

    <app-header [msg]="msg"></app-header>

    在父组件中定义数据

    public msg:string="首页组件的标题"

    2. 子组件引入 Input 模块

    header.component.ts引入:

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

    3. 中 子组件中 @Input 接收父组件传过来的数据

    export class HeaderComponent implements OnInit {

    //接受父组件传来的数据
    @Input() msg:string

    4. 子组件中使用父组件的数据

    header.component.html:

    <h2>这是头部组件--{{msg}}</h2>

    二、 子组件通过@Output 触发父组件的方

    (1)在父组件home.component.ts中定义方法

    例如

    run(){

    alert"我是父组件的run方法")

    }

    (2)在父组件中home.component.html中引入子组件

    <app-header [run]='run'></app-header>

    (3)在子组件header.component.ts

    @input() run:any

     把父组件整个实例传给子组件,子组件可以调用父组件的数据和方法

    1.在父组件中home.component.html中引入子组件

    <app-header [home]='this'></app-header>

    【home】中home为自定义

    2.在子组件header.component.ts

    @Input() home:any;

    三、 父组件通过@ViewChild 主动获取子组
    件的数据和方法

    例如

    父组件:new

    子组件:footer

    1.在父组件中new.component.html中引入子组件

    定义子组件名称

    <app-footer  #footer></app-footer>

    2.子组件footer.component.ts定义数据和方法

     3.父组件中html中

    <button (click)='getchildMSg()'>获取子组件的msg</button>

    <button (click)='getchildrun()'>执行子组件的run</button>

    4.在父组件ts中,引入ViewChild,button中的定义方法

     非父子组件之间传值和共享方法

    1.服务可以实现

    2.Loclstorage

  • 相关阅读:
    正则表达式学习笔记(3)字符类
    一个Service/Functional/Persistence的简单框架
    在Visual Studio 2008环境下安装Boost
    你需要掌握的三种编程语言
    abstract、virtual、override 和 new
    WINCE下编译STLPort
    VS2008环境下编译使用SGI STL(using stlport 5.2.1)
    QT For WinCE, Visual Studio 2008环境的搭建
    VC6.0、VS2005、VS2008安装STLport5.2.1
    Ubuntu 11.10 安装nginx+php5+mysql 的web服务器
  • 原文地址:https://www.cnblogs.com/foremostxl/p/12951682.html
Copyright © 2011-2022 走看看