Angular @input 與 @output

將父元件資料傳到子元件

在子元件引入@angular/core =>Input
@input變數的窗口

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
import { Component,Input } from '@angular/core';
import { CommonModule,Location } from '@angular/common';
import { RouterLink } from '@angular/router';

interface navListType{
title: string,
path: string,
}
@Component({
selector: 'app-navbar', //這是元件的名稱
standalone: true,
imports: [
RouterLink,CommonModule,
],
templateUrl: './navbar.component.html',
styleUrl: './navbar.component.scss'
})
export class NavbarComponent {
@Input() navListsCurrent = '';
@Input() npageTitleCurrent = '';
@Input() isActiveCurrent = '';
//點擊頁面按鈕函式
actionList(path: string) {
this.npageTitleCurrent = path;
}
}

父元件
.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Component, OnInit } from '@angular/core';
import { RouterOutlet ,RouterLink} from '@angular/router';
import {MatButtonModule} from '@angular/material/button';
import { ButtonModule } from 'primeng/button';
import { ToDoComponent } from './components/to-do/to-do.component';
import { NavbarComponent } from './components/navbar/navbar.component';

interface navListType{
title: string,
path: string,
}
@Component({
selector: 'app-root',
standalone: true,
imports: [
RouterOutlet,
MatButtonModule,
ButtonModule,
ToDoComponent,
NavbarComponent,
RouterLink,
],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit{
normalValue='noValue'
constructorValue="noValue"
ngOnInitValue = "noValue"

navLists: navListType[] = [
{ title: 'Home' ,path:'index'},
{title:'FetchData',path:'fetch-data'}
]
//頁面名稱
pageTitle: string = 'Home';
isActive: boolean = false;
constructor() {
console.log('constructor啟動了')
this.constructorValue='從constructor取值'
this.normalValue='從constructor取值'
}
ngOnInit(): void {
console.log('ngOnInit啟動了')
this.ngOnInitValue='從ngOnInit取值'
this.normalValue='從ngOnInit取值'
}
title = 'tode_project';
}

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<main class="main">
<app-navbar
[navListsCurrent]="navLists"
[npageTitleCurrent]="pageTitle"
[isActiveCurrent]="pageTitle"
></app-navbar>

</main>
<div>
<div>normalValue的值:{{normalValue}}</div>
<div> constructor的值:{{constructorValue}}</div>
<div>ngOnInit的值:{{ngOnInitValue}}</div>
</div>
<router-outlet />

@input 父向子傳遞資料


@input 父向子傳遞資料 官網