Angular之输入输出属性

一 父组件

company.component.ts

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

@Component({
  selector: 'app-company',
  templateUrl: './company.component.html',
  styleUrls: ['./company.component.css']
})
export class CompanyComponent implements OnInit {

  employee = 'Tom';
  skill: string;

  constructor() { }

  ngOnInit() {
  }

  releaseSkill(skill: string) {
    this.skill = skill;
  }

}

company.compnent.html

<p>
  company works! {{skill}}
</p>
<app-employee [name]="employee" (releaseSkill)="releaseSkill($event);"></app-employee>

二 子组件

employee.component.ts

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

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  @Input()
  name: string;

  skill: string;

  @Output()
  releaseSkill: EventEmitter<string> = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  perform() {
    this.skill = '摄影';
    this.releaseSkill.emit(this.skill);
  }


}

employee.component.html

<p>
  employee works! {{name}}
</p>
<button type="button" (click)="perform();">表演</button>

三 运行效果

原文地址:https://www.cnblogs.com/sea-breeze/p/8955349.html