angular 父子通信

xiaotou.component.ts

import { Component,OnInit } from '@angular/core';
import { DaTouComponent } from './datou.component';

@Component({
    selector: 'xiaotou',
    template: `
        <h1>这是父组件</h1>
        <datou (toFatherEvent)="rcvMsg($event)" [myValue]="treasure"></datou>
        
    `
})

export class XiaoTouComponent implements OnInit {
    treasure:string="传家宝";
    constructor() { }

    ngOnInit() { }

    rcvMsg(msg:any){
        console.log("儿子传来的信息是"+msg);
    }
}
datou.component.ts

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

@Component({
    selector: 'datou',
    template: `
        <h3>这是子组件</h3>
        <p>{{"父组件传来的值"+myValue}}</p>
        <button (click)="askFather()">问候老爷子</button>
    `
})

export class DaTouComponent implements OnInit {
    @Input() myValue:any="";

    @Output() toFatherEvent=new EventEmitter();
    constructor() { }

    ngOnInit() { }

    askFather(){
        this.toFatherEvent.emit("传家宝是什么?");
    }
}
app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms'

import { AppComponent }  from './app.component';
import {Demo01Component} from './demo01/demo01.component';
import {Demo02Component} from './demo02/demo02.component';
import {Demo03Component} from './demo03/demo03.component';
import {Demo04Component} from './demo04/demo04.component';
import {Demo05Component} from './demo05/demo05.component';
import {Demo06Component} from './demo06/demo06.component';
import {TestDirective} from './demo06/test.directive';
import {XiaoTouComponent} from './demo07/xiaotou.component';
import {DaTouComponent} from './demo07/datou.component';
import {ChatroomComponent} from './demo08/chatroom.component';
import {UserComponent} from './demo08/user.component';

@NgModule({
  imports:      [ BrowserModule,FormsModule ],
  declarations: [ 
    AppComponent,
    Demo01Component,
    Demo02Component,
    Demo03Component,
    Demo04Component,
    Demo05Component,
    Demo06Component,
    TestDirective,
    XiaoTouComponent,
    DaTouComponent,
    ChatroomComponent,
    UserComponent
  ],
  bootstrap:    [ AppComponent ]
})
export class AppModule {}
app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
      <h1>Hello {{name}}</h1>
      <xiaotou></xiaotou>
  `,
})
export class AppComponent  { name = 'New Year'; }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值