详解下angular中的组件里的属性和含义
- 定义组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18@Component({
// 相当于选择器 可以'.app-stock-item'这样就是class选择器就不用写标签了给个div上加上class就行了
//还可以'[app-stock-item]'这样用元素属性使用在<div app-stock-item ></div>
selector: 'app-stock-item',
//模板 页面结构还有种引入页面结构的方法 template:`<div></div>`注意是``不是'',他和url只能出现一个url是相对地址
templateUrl: './stock-item.component.html',
//样式和templateUrl一样,但是他是个数组他可以放多个文件的相对路径,还有种写法是styles:[`div{color:red}`],他和上面的结构一样只能出现一个
styleUrls: ['./stock-item.component.scss'],
//一般angular会在默认的情况下两个同级页面不会相互吃到样式如果是单个样式文件引入各个组件的话,但是不乏一些情况出现可以用encapsulation属性设置
// ViewEncapsulation.Emulated 这是默认值会创建模拟影子和root行为的胶水代码类似于vue的scope
// ViewEncapsulation.Native 这是理想型,会使用影子root这只适用本来就支持他的浏览器和平台
// ViewEncapsulation.None 使用全局
encapsulation:ViewEncapsulation.None,
//剩下的是些其他的东西略写,不太常用删除空白字符、动画、插值、视图提供者、导出组件、变化检测、有空去看官文,不介绍
})
export class StockItemComponent implements OnInit {
} - 输入和输出
父向子传值为输入子向父为输出,为了不影响我们前面的代码我们新建个组件ng generate component stock/Byval
和控制器ng generate class model/stockThree
在.component.html加上输出的值,在.component.ts
这时候在我们父级的组件中也就是app.component.ts里加入1
2
3
4
5
6
7
8
9
10
11
12
13import { Component, Input } from '@angular/core';
import {StockThree} from "../../model/stock-three";
@Component({
selector: 'app-app-stock-item',
templateUrl: './app-stock-item.component.html',
styleUrls: ['./app-stock-item.component.scss']
})
export class AppStockItemComponent {
//这里请注意第一行引入了Input 公开我们的stockThree用这个作为接受传入
@Input() public stockThree:StockThree
constructor() { }
}接下来就是在模板中把这个传入1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import { Component } from '@angular/core';
//下面我也不知道为什么一去掉就会验证路径错误我编辑器问题
// @ts-ignore
import {StockThree} from './model/stock-three';
@Component({
selector: 'app-root', //要转换成组件实例的dom选择器
templateUrl: './app.component.html', //组件所对应的html模板,这里用的是他的url地址
styleUrls: ['./app.component.scss'] //针对组件的样式,这里再次使用了单独的文件来指定
})
export class AppComponent { //组件类,包含它的成员的函数
title = 'demo1';
// 定义个stockObj的变量并且第一次给他赋值下
public stockObj: StockThree;
ngOnInit():void{
this.stockObj=new StockThree('标题00','Tsc',5,5)
}
}
app.component.html中写入传入方法1
<app-app-stock-item [stockThree]="stockObj"></app-app-stock-item>