2021-08-27 angular9学习(二)—— 结构型指令(改变宿主文档结构)

1. angular语法中的*符号

*是一个语法糖,举例:

<a *ngIf="isLogin">退出</a>

等价于:

<ng-template [ngIf]="isLogin">
  <a>退出</a>
</ng-template>

2. 只有一个输入属性时

html使用:

<div *appMyDirective="firstParams">使用结构型指令</div>

.directive.ts指令文件:

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({
  selector: '[appMyDirective]'
})
export class MyDirectiveDirective {

  private hasView = false;

  /**
   * 写法一:
   * 1.@Input()括号里面不写参数名称时,set appMyDirective(val: any) 的属性名一定要跟指令的名称(即selector定义的名称)相同;
   */
  @Input()
  set appMyDirective(val: any) {
  	// val:传入的属性值
    console.log(val, 'val');
    if(val && !this.hasView) {
      // 如果条件为真,创建该模板元素
      this._viewContainer.createEmbeddedView(this._template);
    } else if (!val && this.hasView) {
      this.hasView = false;
      // 否则清空视图
      this._viewContainer.clear();
    }
  }
  
  /**
   * 写法二:
   * 2.当@Input()括号里面有参数时,设置的字符串参数一定要跟指令名称相同时,这时set myDirective(val: any) 的属性名可以不跟指令的名称相同。
   */
  @Input('appMyDirective')
  set myDirective(val: any) {
    console.log(val, 'val',)
    if(val && !this.hasView) {
      // 如果条件为真,创建该模板元素
      this._viewContainer.createEmbeddedView(this._template);
    } else if (!val && this.hasView) {
      this.hasView = false;
      // 否则清空视图
      this._viewContainer.clear();
    }
  }

  constructor(
    private _template: TemplateRef<any>,
    private _viewContainer: ViewContainerRef
  ) { }

}

3. 有多个输入属性时

html使用,注意:从第二个参数开始,要通过键值对的方式传入,多个参数使用;分隔。

<div *appMyDirective="firstParams;secondParams: secondParams;">使用结构型指令</div>

.directive.ts指令文件,注意:这里跟只有一个输入属性时一样,也是两种书写方式,且这里的输入属性名appMyDirectiveSecondParams的格式为 指令名称 + 绑定的参数的键值名且首字母大写 appMyDirective + SecondParams

// 方式一:
@Input()
set appMyDirectiveSecondParams(val: any) {
  console.log(val, 'val',)
    
}

// 方式二:
@Input('appMyDirectiveSecondParams')
set appMyDirectiveSecondParams(val: any) {
  console.log(val, 'val',)
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值