Java教程

angular技巧

本文主要是介绍angular技巧,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

withLatestFrom

将源 Observable 与其他 Observable 组合以创建一个 Observable,其值从每个 Observable 的最新值计算,仅当源发出时。

拿到最新的值进行合并

 const sportsNews$ = interval(5000).pipe(
      map(i => `One News ${i}`)
    );

    const worldNews$ = interval(1000).pipe(
      map(i => `Two News ${i}`),
      // tap((v) => console.log(v))
    );
    const customizedNews$ = sportsNews$.pipe(
      withLatestFrom(worldNews$),
      map(([sportNews, worldNews]) => `One: ${sportNews}; Two: ${worldNews}`),
      take(3)
    );
    customizedNews$.subscribe(console.log);

// One: One News 0; Two: Two News 4
// One: One News 1; Two: Two News 9
// One: One News 2; Two: Two News 14

sample

如果不用上面那种方式

  const news$ = interval(1000).pipe(
      map(i => `News ${i}`)
    );

    const latestNews$ = news$.pipe(
      sample(interval(5000)),// 每5s拿到最新的值
      take(3)
    );

    latestNews$.subscribe(console.log);

禁用当前选中

<mat-form-field>
  <mat-select
    [(ngModel)]="selectedBrands"
    [ngModelOptions]="{ standalone: true }"        
    required multiple
  >
    <mat-option
      *ngFor="let brand of brands"
      [value]="brand"
      [disabled]="selectedBrands.indexOf(brand) > -1"
      >{{ brand.name }}
    </mat-option>
  </mat-select>
</mat-form-field>

任意时区的当前时区

// 获取当前时区
const num=- new Date().getTimezoneOffset() / 60;

const newDate=new Date(new Date().getTime()+num*60*60*1000).toISOString()

pluck

从具有多个属性的数组中提取单个属性。

 from([
      { brand: 'Apple', model: 'max 12 pro', price: '$10'},
      { brand: 'Nokia', model: 'X 10', price: '$50'}
    ]).pipe(pluck('model'))
      .subscribe(console.log)

// max 12 pro
// X 10

枚举的实际使用

export enum Test1 {
  num1 = 'left',
  num2 = 'right'
}

export class TimeSevenComponent implements OnInit, AfterViewInit {
  eye = Test1;
  ngOnInit(): void {
    console.log(this.eye);
  }
}

空值的使用

<h1 [ngClass]="null??'xxxx'">Hello World</h1>

angular早期的表单

<input type="text" [ngModel]="sexNum" #foo="ngModel" required (ngModelChange)="setChange($event,foo)">
{{foo.value}} {{foo.errors|json}}

 sexNum=''
 setChange($event: any, foo: NgModel) {
    console.log($event, foo);
  }

案例二

<form #f="ngForm">
  <input type="text" name="one" ngModel #foo="ngModel" required (ngModelChange)="setChange($event,foo)">
  {{f.value |json}}
</form>

 ngForm = {
    one: '',
    two: '',
  };

angular13

删除ng add包, 如果使用请使用yarn ng add

添加@angular/elements

angualr13别用webstrom20210203 还是有问题

typescript

export type TypeTwo='a'|'b'
export type TypeOne = 'c' | 'd';
export type TypeThree=`${TypeOne}我是谁${TypeTwo}`
  a: TypeThree = 'd我是谁a';

超时报错

模拟延迟请求
const obj = new BehaviorSubject('bbbb');
obj.pipe(delay(1000*4))
// 案例
 obj.pipe(delay(1000*4)).pipe(
      timeout(1000 * 4),
      catchError((error: any) => {
        return throwError('报错了')
      })
    ).subscribe(console.log);

输入框失去焦点清空两边空格的指令

@Directive({
  selector: '[tyFormBlur]'
})
export class FormBlurDirective implements OnInit {

  constructor(private elementRef: ElementRef, @Self() private ngControl: NgControl) {
  }

  ngOnInit(): void {
    // 失去焦点, 清空两边空格
    fromEvent(this.elementRef.nativeElement, 'blur').subscribe(() => {
      if (typeof this.ngControl.value === 'string') {
        const value = this.ngControl.value.trim();
        this.ngControl.control.patchValue(value);
      }
    })
  }
}

promise /observable 转化

   fromPromise(Promise.resolve('xxx')).subscribe(console.log)
    of(1).toPromise().then(console.log)

form表单

ngOnInit(): void {
    this.form = this.formBuilder.group({
      firstName: [{ value: 'Foo', disabled: true }, [Validators.required]],
      lastName: ['Bar']
    });
    this.lastName.disable();
  }

ng-template

<ul>
  <li *ngFor="let item of arr">
    <ng-container *ngTemplateOutlet="sex;context:item"></ng-container>
  </li>
</ul>
<ng-template #sex let-names>
  <h1>我是一个{{names}}</h1>
</ng-template>

  arr:Array<any>=[1,2,3]
这篇关于angular技巧的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!