codememo

*ng템플릿에 있는 경우

tipmemo 2023. 4. 28. 20:36
반응형

*ng템플릿에 있는 경우

한 번에 어떻게 여러 사례가*ngIf진서? Vue Angular 1에 if,else if,그리고.else는 Angular 4만 것 같습니다.true(if및 ) 및false(else . 조건.

문서에 따르면, 저는 다음과 같은 작업만 수행할 수 있습니다.

<ng-container *ngIf="foo === 1; then first else second"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>

하지만 저는 여러 가지 조건을 갖고 싶습니다.

<ng-container *ngIf="foo === 1; then first; foo === 2; then second else third"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>

하지만 저는 결국 사용할 수 밖에 없습니다.ngSwitch해킹처럼 느껴집니다.

<ng-container [ngSwitch]="true">
  <div *ngSwitchCase="foo === 1">First</div>
  <div *ngSwitchCase="bar === 2">Second</div>
  <div *ngSwitchDefault>Third</div>
</ng-container>

또는 Angular 1과 Vue에서 익숙해진 많은 구문이 Angular 4에서 지원되지 않는 것 같습니다. 그렇다면 이러한 조건으로 코드를 구성하는 권장 방법은 무엇입니까?

또 다른 대안은 조건을 중첩하는 것입니다.

<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
    <ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>

다음을 사용할 수 있습니다.

<ng-template [ngIf]="index == 1">First</ng-template>
<ng-template [ngIf]="index == 2">Second</ng-template>
<ng-template [ngIf]="index == 3">Third</ng-template>

ng-container 부분이 당신의 디자인에 중요하지 않다면, 나는 생각합니다.

여기 플런커가 있습니다.

이것이 가장 깨끗한 방법인 것 같습니다.

if (foo === 1) {

} else if (bar === 99) {

} else if (foo === 2) {

} else {

}

템플릿에서:

<ng-container *ngIf="foo === 1; else elseif1">foo === 1</ng-container>
<ng-template #elseif1>
    <ng-container *ngIf="bar === 99; else elseif2">bar === 99</ng-container>
</ng-template>
<ng-template #elseif2>
    <ng-container *ngIf="foo === 2; else else1">foo === 2</ng-container>
</ng-template>
<ng-template #else1>else</ng-template>

조건에 서로 다른 변수가 포함된 경우(한 번에 하나의 경우만 해당) 적절한 문처럼 작동합니다.이러한 경우 다른 답변 중 일부는 제대로 작동하지 않습니다.

못생겼어요.: 에세상그, 정못요어겼생말옆건.else if템플릿 코드...

상황에 따라 여러 가지 방법을 사용할 수 있습니다.

  1. 변수가 특정 숫자 또는 문자열로 제한되는 경우 ngSwitch 또는 ngIf를 사용하는 것이 가장 좋습니다.

    <!-- foo = 3 -->
    <div [ngSwitch]="foo">
        <div *ngSwitchCase="1">First Number</div>
        <div *ngSwitchCase="2">Second Number</div>
        <div *ngSwitchCase="3">Third Number</div>
        <div *ngSwitchDefault>Other Number</div>
    </div>
    
    <!-- foo = 3 -->
    <ng-template [ngIf]="foo === 1">First Number</ng-template>
    <ng-template [ngIf]="foo === 2">Second Number</ng-template>
    <ng-template [ngIf]="foo === 3">Third Number</ng-template>
    
    
    <!-- foo = 'David' -->
    <div [ngSwitch]="foo">
        <div *ngSwitchCase="'Daniel'">Daniel String</div>
        <div *ngSwitchCase="'David'">David String</div>
        <div *ngSwitchCase="'Alex'">Alex String</div>
        <div *ngSwitchDefault>Other String</div>
    </div>
    
    <!-- foo = 'David' -->
    <ng-template [ngIf]="foo === 'Alex'">Alex String</ng-template>
    <ng-template [ngIf]="foo === 'David'">David String</ng-template>
    <ng-template [ngIf]="foo === 'Daniel'">Daniel String</ng-template>
    
  2. 위는 코드 및 동적 코드의 경우 적합하지 않습니다. 아래 코드를 사용할 수 있습니다.

    <!-- foo = 5 -->
    <ng-container *ngIf="foo >= 1 && foo <= 3; then t13"></ng-container>
    <ng-container *ngIf="foo >= 4 && foo <= 6; then t46"></ng-container>
    <ng-container *ngIf="foo >= 7; then t7"></ng-container>
    
    <!-- If Statement -->
    <ng-template #t13>
        Template for foo between 1 and 3
    </ng-template>
    <!-- If Else Statement -->
    <ng-template #t46>
        Template for foo between 4 and 6
    </ng-template>
    <!-- Else Statement -->
    <ng-template #t7>
        Template for foo greater than 7
    </ng-template>
    

참고: 모든 형식을 선택할 수 있지만 모든 코드에는 고유한 문제가 있습니다.

아니면 3진 연산자가 있는 조건부 체인을 사용할 수도 있습니다. if … else if … else if … else쇠사슬의

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator#Conditional_chains

<ng-container [ngTemplateOutlet]="isFirst ? first : isSecond ? second : third"></ng-container>

<ng-template #first></ng-template>
<ng-template #second></ng-template>
<ng-template #third></ng-template>

저는 이 방법이 더 좋습니다.

nesting과 ngSwitch를 피하기 위해 논리 연산자가 Javascript에서 작동하는 방식을 활용하는 다음과 같은 가능성도 있습니다.

<ng-container *ngIf="foo === 1; then first; else (foo === 2 && second) || (foo === 3 && third)"></ng-container>
  <ng-template #first>First</ng-template>
  <ng-template #second>Second</ng-template>
  <ng-template #third>Third</ng-template>

ng-container를 사용하는 경우 *ngIf를 사용할 필요가 없습니다.

<ng-container [ngTemplateOutlet]="myTemplate === 'first' ? first : myTemplate === 
   'second' ? second : third"></ng-container>

  <ng-template #first>first</ng-template>
  <ng-template #second>second</ng-template>
  <ng-template #third>third</ng-template>

<ion-row *ngIf="cat === 1;else second"></ion-row>
<ng-template #second>
    <ion-row *ngIf="cat === 2;else third"></ion-row>
</ng-template>
<ng-template #third>

</ng-template>

Angular는 우리가 항상 사용하는 많은 구조적 지시어에서 이미 후드 아래에 ng-template를 사용하고 있습니다. ngIf, ngFor 및 ngSwitch.

> 앵귤러에서 ng-template란 무엇입니까?

https://www.angularjswiki.com/angular/what-is-ng-template-in-angular/

는 이런 . ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ*ngIf elseIf else그리고 나는 그것을 사용하여 해결했습니다.ng-template다음 스니펫이 간략하게 묘사되기를 바랍니다.

"NIC"라는 이름의 양식 컨트롤이 있으며 양식 컨트롤이 유효하지 않을 때 한 번에 하나의 오류 메시지를 표시해야 합니다.

form: FormGroup = new FormGroup({
    NIC: new FormControl('', [Validators.required, Validators.minLength(10), Validators.maxLength(10), Validators.pattern("^[0-9]*$")])
  });

템플릿

<mat-form-field appearance="standard">
    <mat-label>NIC Number</mat-label>
    <input matInput placeholder="Enter NIC no" formControlName="NIC">
    <mat-error *ngIf="form.controls['NIC'].errors?.required; else minvalue">This field is mandatory.
    </mat-error>

    <ng-template #minvalue>
        <mat-error *ngIf="form.controls['NIC'].errors?.minlength; else maxvalue">Minimum 10 charactors
            needed.
        </mat-error>
    </ng-template>

    <ng-template #maxvalue>
        <mat-error *ngIf="form.controls['NIC'].errors?.maxLength; else numericonly">Maximum 10
            charactors allowed.
        </mat-error>
    </ng-template>

    <ng-template #numericonly>
        <mat-error *ngIf="form.controls['NIC'].errors?.pattern">
            Numeric characters only.
        </mat-error>
    </ng-template>

</mat-form-field>

Angular에서 ngSwitch 지시문을 사용하여 *ngIf 문에 여러 개의 대소문자를 포함하는 기능을 수행할 수 있습니다.다음은 예입니다.

<div [ngSwitch]="foo">
  <ng-template [ngSwitchCase]="1">First</ng-template>
  <ng-template [ngSwitchCase]="2">Second</ng-template>
  <ng-template [ngSwitchCase]="3">Third</ng-template>
  <ng-template ngSwitchDefault>Default</ng-template>
</div>

또는 *ngIf-then-else 연산자와 3진 연산자를 사용할 수도 있습니다.

<ng-container *ngIf="isFirst; then first; else (isSecond ? second : third)"></ng-container>

<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>

일부 변수가 여러 값을 취할 수 있는 간단한 경우(예:foo의 것입니다.1 | 2 | 3type) 그럼 그냥 플레인을 사용하세요.ngSwitch:

<ng-container [ngSwitch]="foo">
    <div *ngSwitchCase="1">First</div>
    <div *ngSwitchCase="2">Second</div>
    <div *ngSwitchCase="3">Third</div>
</ng-container>

하지만, 만약 당신이 더 세련된 것이 필요하다면.if-else논리는 필요한 상태의 집합을 사용하여 구성 요소 함수 내에서 설명하는 것이 더 낫고 명확할 수 있습니다.

getLandformType(): 'continent' | 'island' | 'peninsula' {
  if(this.pieceOfLand.bigEnough){
    return 'continent';
  }
  else if(this.pieceOfLand.surroundedByWater){
    return 'island';
  }
  return 'peninsula';
}

다시 말하지만, 이를 통해 처리할 수 있습니다.ngSwitch:

<ng-container [ngSwitch]="getLandformType()">
  <div *ngSwitchCase="'continent'">Continent</div>
  <div *ngSwitchCase="'island'">Island</div>
  <div *ngSwitchCase="'peninsula'">Peninsula</div>
</ng-container>

또한 이 접근 방식은 세 가지 다른 옵션과 달리 한 번에 하나의 옵션만 이길 수 있습니다.*ngIf(미포함else블록들

이 오래된 트릭을 사용하여 복잡한 if/then/else 블록을 약간 더 깨끗한 스위치 문으로 변환할 수도 있습니다.

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

언급URL : https://stackoverflow.com/questions/43812770/ngif-else-if-in-template

반응형