组件封装的意义和方法
需要重用,或者简化逻辑
ng generate component组件名 (驼峰模式)
使用index.ts方便导入以及隔离内部变化对外部的影响
ng g c 组件名(驼峰模式)
如果想在某个文件夹下新建组件 ng g c 文件名/组件名(驼峰模式)
在每一个文件夹下新建一个index.ts 引用
每一个组件里 export * from './scrollable-tab.component';
大组件文件夹下 export * from './scrollable-tab'
组的输入输出件
父组件 -> 子组件 @input 属性绑定
子组件 -> 父组件 @output 事件绑定
1.父组件引用子组件 父组件数据传到子组件
父组件
app.component.html
app.component.ts
import { Component } from '@angular/core';
import { TopMenu } from './components';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
menus:TopMenu[] = [
{
title:'热门',
link:''
},
{
title:'男装',
link:''
},
{
title:'家纺',
link:''
},
{
title:'食品',
link:''
},
{
title:'电器',
link:''
},
{
title:'鞋包',
link:''
},
{
title:'汽车',
link:''
}
];
menus1:TopMenu[] = [
{
title:'男装',
link:''
},
{
title:'百货',
link:''
},
{
title:'运动',
link:''
},
{
title:'手机',
link:''
},
{
title:'家纺',
link:''
}
];
}
子组件
scrollable-tab.component.html
scrollable.component.ts
import { Component, OnInit ,Input} from '@angular/core';
export interface TopMenu {
title:string;
link?:string;
}
@Component({
selector: 'app-scrollable-tab',
templateUrl: './scrollable-tab.component.html',
styleUrls: ['./scrollable-tab.component.css']
})
export class ScrollableTabComponent implements OnInit {
selectedIndex = 0;
@Input() menu : TopMenu[] = [];
constructor() { }
ngOnInit() {
}
}
2.父组件引用子组件 子组件数据传到父组件
子组件:scrollable.component.html
scrollable.component.ts
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
export interface TopMenu {
title:string;
link?:string;
}
@Component({
selector: 'app-scrollable-tab',
templateUrl: './scrollable-tab.component.html',
styleUrls: ['./scrollable-tab.component.css']
})
export class ScrollableTabComponent implements OnInit {
selectedIndex = 0;
@Input() menu : TopMenu[] = [];
@Output() tabSelected = new EventEmitter();
constructor() { }
ngOnInit() {
}
handleSelection(index : number){
this.selectedIndex = index;
this.tabSelected.emit(this.menu[this.selectedIndex])
}
}
父组件:
handelTabSelected(a:TopMenu){
console.log(a)
}