Angular 子傳父「傳值」

子元件藉由@Output裝飾器定義屬性,該屬性為EventEmitter實體,可以設定要傳送的資料型別,透過事件繫結(Event Binding)通知父元件有事件發生。

子元件

1在子元件類中匯入 Output 和 EventEmitter
1
import { Output, EventEmitter } from '@angular/core';
2@Output() newPageTitle = new EventEmitter();
1
2
3
4
5
6
export class NavbarComponent implements OnInit{
@Output() newPageTitle = new EventEmitter<string>();
sendActionList(path: string) {
+ this.newPageTitle.emit(path);
}
}
舉例 ex:Navbar
TS
在子元件類中匯入 Output 和 EventEmitter
NgFor 必須載入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
+ import { Component, Input, OnInit,EventEmitter, Output } from '@angular/core';
+ import { NgFor } from '@angular/common';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
import { navListType } from '../../Type/nav';
@Component({
selector: 'app-navbar',
imports: [
+ NgFor,
CommonModule,
RouterLink
],
templateUrl: './navbar.component.html',
styleUrl: './navbar.component.scss',
})

export class NavbarComponent implements OnInit{
// 子傳父
+ @Input() sendNavLists!: navListType[];
+ @Input() sendPageTitle!: string;
+ @Input() sendIsActive!: boolean;
// 父傳子 @Output() 欄位 = new EventEmitter<屬性>();
+ @Output() newPageTitle = new EventEmitter<string>();
//點擊頁面按鈕函式
sendActionList(path: string) {
//this.欄位.emit()
+ this.newPageTitle.emit(path);
}
ngOnInit(): void {

}
}
HTML
*ngFor 陣列方式迴圈
[ngClass] 動態Class
[routerLink] 動態Class
(click) 點擊函式
1
2
3
4
5
6
7
8
 <ul  class="nav">
<li *ngFor="let item of sendNavLists ; let i = index"
[ngClass]="sendPageTitle === item.title ? 'activeNav' : ''">
<a [routerLink]="item.path"
(click)="sendActionList(item.title)"
class="cursor-pointer">{{item.title}}</a>
</li>
</ul>
父元件
Html
(newPageTitle)="actionList($event)" => @Output() 藉由newPageTitle 通訊
1
2
3
4
5
6
7
8
9
10
<app-navbar
[sendNavLists]="navLists"
[sendPageTitle]="pageTitle"
[sendIsActive]="isActive"
+ (newPageTitle)="actionList($event)"
></app-navbar>

<main class="main">
<router-outlet />
</main>

TS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { environment } from '../environments/environment';
import { NavbarComponent } from "./components/navbar/navbar.component";
import { navListType } from "./Type/nav";

@Component({
selector: 'app-root',
imports: [
RouterOutlet,
FormsModule,
NavbarComponent,
],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})

export class AppComponent {
title = "我的網站";
navLists: navListType[] = [
{ title: 'Home' ,path:'/'},
{ title: 'Users', path: 'user' },
{title:'Login',path:'login'}
]
pageTitle: string = 'Home';
isActive: boolean = false;
+ actionList(path: string) {
+ this.pageTitle = path;
+ }
ngOnInit(): void {
console.log(environment.production ? 'Production' : '開發中')
}
}