angular @Input() 和 @Output()

來源:互聯網
上載者:User

標籤:cli   angular   delete   對象   button   component   組件   rom   []   

建立 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

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

@Input() 很簡單,就是將父組件的資料給子組件的一個屬性;
@Output() 子組件建立一個 EventEmitter, 子組件的操作會觸發EventEmitter ,然後將這個 EventEmitter 對象賦值給 父組件的一個 method ,改方法會拿到EventEmitter對象給的參數,然後進行處理;

angular @Input() 和 @Output()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.