了解一下angular中的@Input()和@Output()-LMLPHP

创建 Student class

就只有几个简单的属性(执行下面的属性可以快速生成)
ng generate class entity/student

export class Student {
    id: number;
    name: string;
    age: number;
}
登录后复制

创建child component

ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Student } from '../entity/student';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() stu: Student;
  @Output() deleteEvent = new EventEmitter<number>();
  constructor() { }
  ngOnInit() {
  }
  delete(id) {
    this.stu = null;
    this.deleteEvent.emit(id);
  }
}
登录后复制

html

<p *ngIf="stu">
  {{stu.id}} -- {{stu.name}} -- {{stu.age}}  <button (click)="delete(stu.id)">delete</button>
</p>
登录后复制

修改 app.component

ts

import { Component } from '@angular/core';
import { Student } from './entity/student';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  stus: Student[] = [
    {id: 1, name: '里斯', age: 3},
    {id: 2, name: '里斯2', age: 4},
    {id: 3, name: '里斯3', age: 5},
  ];
  stu: Student;
  constructor() {
  }
  selected(stu) {
    this.stu = stu;
  }
  deleteStu(id: number) {
    this.stus.forEach((val, index) => {
      if ( val.id === id) {
        this.stus.splice(index, 1);
        return;
      }
    });
  }
}
登录后复制

html

<p>
  <ul>
    <li *ngFor="let stu of stus" (click)="selected(stu)"> {{stu.id}} -- {{stu.name}} -- {{stu.age}} </li>
  </ul>
</p>
<app-child [stu]="stu" (deleteEvent)="deleteStu($event)"></app-child>
登录后复制

@Input() 很简单,就是将父组件的数据给子组件的一个属性;
@Output() 子组件创建一个 EventEmitter, 子组件的操作会触发EventEmitter ,然后将这个 EventEmitter 对象赋值给 父组件的一个 method ,改方法会拿到EventEmitter对象给的参数,然后进行处理;

更多编程相关知识,可访问:编程教学!!

以上就是了解一下angular中的@Input()和@Output()的详细内容,更多请关注Work网其它相关文章!

08-26 18:53