angular9的学习(十四)

简单说的一些,我的所有文章基本都是个人的差缺补漏,学习的本身本来就是查缺补漏的,其中大量的时间都是花在看资料,吸收一下有价值的东西,然后我会把一些有价值的东西提取出来,只求有生之年能成为大佬

创建模块

ng g m homes --route home --module app

创建一个模块,在根模块appModule指定一个home的懒路由,会在homes-routing,定义一个空的homesComponent组件和路由

验证状态的修改statusChange

 this.fromDate1.get('firstName').statusChanges.subscribe(res => {
     // res== VALID  有效的
     // invalid  无效的
     console.log(res);
     console.log(this.fromDate1.get('firstName').status);// 两个的值是一样的,都是拿到最新的校验状态
    });
// 比如,如果验证通过我们就添加校验
	if(res=='VALID'){
        setValidators 添加校验
	    clearValidators  删除校验
        // 然后必须更新下才能生效
        updateValueAndValidity()
    }

值修改,设置校验

// valueChanges 是检测出值修改的
this.password.valueChanges.subscribe(
  pwd => {
	this.confirmPassword.setValidators([Validators.required, confirmPasswordValidator(pwd)]);        //设置校验
	this.confirmPassword.updateValueAndValidity();// 然后更新
  }
);

 get confirmPassword() {
    return this.userForm.get('confirmPassword');
  }   

修改值不让出发statusChanges事件

this.reactiveForm.get("firstname").setValue("", { emitEvent: false });

只自身被触发但是父级不会被触发

this.reactiveForm.get("firstname").setValue("", { onlySelf: true });

简单的说emitEventonlySef 的效果都同时适用于valueChangesstatusChanges事件

双向数据绑定监听绑定的值

<input [(ngModel)]="num" (ngModelChange)="add($event)">
 add(s) {
    console.log(s);
  }

官网从v6开始就不建议在表单中使用,后续可能会被废除

但是我在v10中使用是正常的

百分比管道PercentPipe

{{nums|percent:'a.b-c'}}
a 最小的整数位,默认1
b 小数点后最小的位数,默认0
c 小数点后最大位数,默认0

num1=0.123
{{nums|percent}}
// 12%
{{nums|percent:'1.2-2'}}
// 12.30%  保留两位小数

async管道

 public obs = new Observable(obser => {
    setTimeout(() => {
      obser.next('sss');
    }, 1000);
  });

<div *ngIf="(obs|async) as value;else elseBlock">
  {{value}}
</div>
<ng-template #elseBlock>
  Observable is loading. Please wait
</ng-template>

异步管道和ngFor组合

 public obs = new Observable(obser => {
    setTimeout(() => {
      obser.next({"message":["afghan","basset","blood","english","ibizan","plott","walker"],"status":"success"}
      );
    }, 1000);
  });

<ul>
  <li *ngFor="let breed of (obs|async)?.message">
    {{breed}}
  </li>
</ul>
=========
<ul *ngIf="(obs|async) as breeds">
  <li *ngFor="let item of breeds.message">{{item}}</li>
</ul>      

OnChanges 生命周期

父传子的时候,检测出每个输入属性的更改

<app-one [count]="count"></app-one>
<button (click)="add()">++</button>
<button (click)="methods()">--</button>
------------
 public count = 1;
  add(): void {
    this.count++;
  }
  methods(): void {
    this.count--;
  }

接受属性,利用OnChanges 检测每个值的修改

  @Input('count') count;
  ngOnChanges(changes: SimpleChanges): void {
    console.log(changes);

  }
previousValue:any 之前的值
currentValue:any 新值
firstChange():boolean 是否是第一次的值Boolean

Form 禁用启用

禁用某个值
 this.reactiveForm.get("email").disable();
启用某个值
 this.reactiveForm.get("address").enable();
禁用所有
this.reactiveForm.disable();
启用所有
this.reactiveForm.enable();

FormArray 添加某个值

newSkill(): FormGroup {
   return this.fb.group({
     skill: '',
     exp: '',
   })
}
// 动态增加
addSkills() {
   this.skills.push(this.newSkill());
}

FormArray 删除元素

this.skills.removeAt(i)

FormArray的使用

  <div formArrayName="skills">
    <div *ngFor="let skill of skills().controls; let i=index">
      <div [formGroupName]="i">
        {{i}}
        skill name :
        <input type="text" formControlName="skill">
        exp:
        <input type="text" formControlName="exp">
 
        <button (click)="removeSkill(i)">Remove</button>
      </div>
    </div>
  </div>

拿到FormArray 的某一项

  this.teachersForm = this.fb.group({
      teachers: this.fb.array([
          this.fb.group({
     		 name: '',
   			 batches: this.fb.array([])
  			  })
      ]),
    })
// 拿到数组
 teachers(): FormArray {
    return this.teachersForm.get("teachers") as FormArray
  }
// 拿到某个子数组的 batches
  batches(ti): FormArray {
    return this.teachers().at(ti).get("batches") as FormArray
  }

下拉框提示语

 <select formControlName="country">
    <option [ngValue]="null" disabled>提示语</option>
    <option *ngFor="let country of countries" [ngValue]="country.id">{{country.name}}</option>
  </select>

Form 验证器

firstname: new FormControl('',[Validators.required,Validators.minLength(10),Validators.maxLength(15),Validators.pattern("^[a-zA-Z]+$"),Validators.email]),

禁用提交

<button type="submit" [disabled]="!contactForm.valid">Submit</button>

错误信息

  <div
    *ngIf="!firstname?.valid && (firstname?.dirty ||firstname?.touched)">
    <div [hidden]="!firstname.errors.required">
      First Name is required
    </div>
    <div [hidden]="!firstname.errors.minlength">
      Min Length is 10
    </div>
  </div>

发现一个重要的忽略的知识点,自定义校验器,传递参数

export function gte(val: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    let v: number = +control.value;
    if (isNaN(v)) {
      return { 'gte': true, 'requiredValue': val }
    }
    if (v <= +val) {
      return { 'gte': true, 'requiredValue': val }
    }
    return null;
  }
}
public teaForm: FormGroup;
this.teaForm = this.fb.group({
      firstName: ['',[gte(10)]]
    });
posted @ 2020-07-08 16:11  猫神甜辣酱  阅读(304)  评论(0编辑  收藏  举报