1 代碼結構
2 myc02.component.html
<p>myc02 works!</p> <h4>{{name}}</h4> <h4>{{age}}</h4>
3 myc02.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-myc02', templateUrl: './myc02.component.html', styleUrls: ['./myc02.component.css'] }) export class Myc02Component implements OnInit { name = '我是myc02'; age = 22; show() { alert("我是myc02"); } constructor() { } ngOnInit(): void { } }
4 app.component.html
<button (click)="change()">修改第一個myc02的 name 值</button> <!--給要掌控的子組件一個唯一標識:類似 id="xxx"--> <!--簡化寫法:語法糖 類似css #代替了id--> <app-myc02 #myc02></app-myc02> <app-myc02></app-myc02> <app-myc02></app-myc02>
5 app.component.ts
import { Component, ViewChild } from '@angular/core'; import { Myc02Component } from './myc02/myc02.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ngPro'; //查看子組件中#myc02的哪個組件 //查看子組件中#myc02的哪個組件 @ViewChild('myc02') test!: Myc02Component; change() { //如何在代碼中,拿到子組件的索引 console.log(this.test) //修改abc的name屬性 this.test.name = '你是第一個孩子!!!'; this.test.age += 10; this.test.show(); } }
6 運行效果