angular-组件

组件

创建组件

ng g c 文件夹/组件名称

ng g c componets/child

1.在components 文件夹创建一个

child 文件夹

.html 模板

.css css

.ts  组件类

.spc.ts 测试文件

app.module.ts 导入和注册创建的组件

组件

组件的装饰器

@Component({

  selector: 'app-child',

  templateUrl: './child.component.html',

  styleUrls: ['./child.component.css']

})

selector 引用的标签

templateUrl 组件的模板

styleUrls 组件的css

组件的类

export class ChildComponent implements OnInit {

}

implements 实现接口

OnInit 组件的生命周期 -初始化

组件参数的传递

父传子

<app-child [list]="list">

@Input () list:string[];

子传父

  @Output() selNum = new EventEmitter();

selNum.emit("数据")

<app-child [list]="list" (selNum)="$event">

父获取子 通过ref

<app-child #child2>

{{child2.list}}

child的list数据必须是public

#ref

<p #refp>

import { Component, ViewChild, ElementRef, QueryList, ViewChildren } from '@angular/core';

导入组件

@ViewChild("refp",{static:true}) refp:ElementRef

获取操作dom

ngAfterViewInit(){

  this.refp.nativeElement  //真正的dom节点

}

<div *ngFor="#myitem">

@viewChildren("myitem") myitem:<QueryList>[ElementRef]

ngAfterViewInit(){

  this.myitem.forEach(item=>{

    item.nativeElement //真正的节点

  })

}

服务service

组件间共享的数据和方法

提供服务的

创建 ng g s 文件夹/服务名称

ng g s service/search

使用

1. import {searchService} from 'xxxx'

2. 注入

constructor(private searchService:searchService){}

2. 使用  this.searchService.xxx

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。