下载APP

Angular

组件

@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
  styleUrls: ['./component-overview.component.css']
})

1-1 组件生命周期:

  • ngOnchanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

1-2 视图封装

Component 的装饰器提供了encapsulation选项,可用来控制如何基于每个组件应用视图封装。

@Component({
  encapsulation: ViewEncapsulation.None,
})

有三个值, Emulated、None、ShadowDom

Emulated 是推荐和默认的模式,只会影响组件模板中的元素

None 会将该组件的样式变成全局样式并且添加到文档的<Head>

ShadowDom 用浏览器内置的Shadow DOM API,但这个有兼容性问题

1-3 组件交互

  • 父组件向子组件传值通过 @Input装饰器,并且子组件可以通过setter或者ngOnChanges() 对输入值做一些监听和改变
export class HeroChildComponent {
    @Input() hero!: Hero;
    @Input('master') masterName = '';
}
  • 父组件监听子组件的事件 通过子组件暴露EventEmitter属性,子组件通过这个属性emit事件
export class VoterComponent {
  @Output() voted = new EventEmitter<boolean>();

  vote(agreed: boolean) {
    this.voted.emit(agreed);
  }
}

父组件

@Component({
  selector: 'app-vote-taker',
  template: `
    <app-voter
      *ngFor="let voter of voters"
      [name]="voter"
      (voted)="onVoted($event)">
    </app-voter>
  `
})

模板

文本插值

<h3>Current customer: {{ currentCustomer }}</h3>

模板语句

<button type="button" (click)="deleteHero()">Delete hero</button>

管道

<p>The hero's birthday is {{ birthday | date }}</p>

指令

  • NgClass
  • NgStyle
  • ngModel
  • NgIf
  • NgFor
  • NgSwitch

依赖注入

添加@Injectable装饰器表明此类可以被注入

@Injectable()
class HeroService {}

一个组件可以有多个Service注入,同时Service里面也可以注入Service

export class HeroDetailComponent implements OnInit {
  @Input() hero?: Hero;

  constructor(
    private route: ActivatedRoute,
    private heroService: HeroService,
    private location: Location,
    private messageService: MessageService
  ) {}
 }
在线举报