programing

각도 2 요소 표시 및 숨기기

css3 2023. 3. 26. 11:38

각도 2 요소 표시 및 숨기기

Angular 2의 부울 변수에 따라 요소를 숨기고 표시하는 데 문제가 있습니다.

div가 표시하고 숨길 코드는 다음과 같습니다.

<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

변수는 "변수"이며 내 컴포넌트에 저장됩니다.

export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }, 3000);
  }
}

요소가 숨겨져 있어 saveTodos 기능이 시작되면 요소가 표시되지만, 3초 후에 변수가 false로 돌아와도 요소는 숨겨지지 않습니다. 왜일까요?

달성해야 할 항목에 따라 다음 두 가지 옵션이 있습니다.

  1. 숨겨진 지시어를 사용하여 요소를 표시하거나 숨길 수 있습니다.

    <div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    
  2. ngIf 컨트롤 디렉티브를 사용하여 요소를 추가하거나 삭제할 수 있습니다.이것은 요소를 표시하거나 숨기지는 않지만 DOM에서 추가/제거하기 때문에 숨겨진 지시문과는 다릅니다.요소의 저장되지 않은 데이터를 느슨하게 할 수 있습니다.편집 컴포넌트를 취소하는 것이 좋습니다.

    <div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    

3초 후에 변경되는 문제는 set Timeout과의 비호환성 때문일 수 있습니다.페이지에 angular2-polyfiles.js 라이브러리를 포함했습니까?

*ngIf 디렉티브를 사용해야 합니다.

<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

업데이트: 타임아웃 콜백 내에 있을 때 외부 스코프에 대한 참조가 누락되었습니다.

위에 추가한 것과 같이 .bind(이것)를 추가합니다.

Q : edited는 글로벌 변수입니다.*ngFor-loop 내에서의 접근 방식은 무엇입니까?– Blauhirn

A : 반복하는 오브젝트에 속성으로 편집을 추가합니다.

<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{
   
  public listOfObjects = [
    {
       name : 'obj - 1',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    } 
  ];
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

Html 돔 엘리먼트를 삭제할 필요가 없는 경우 *ngIf를 사용합니다.

그 이외의 경우는, 다음과 같이 합니다.

<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
   COUNTER: {{numberOfUnreadAlerts}} 
</div>

하위 구성 요소가 사용 중임을 표시하기 위해*ngif="selectedState == 1"

그 대신 나는 그것을 사용했다.[hidden]="selectedState!=1"

나한테는 효과가 있었어하위 구성 요소를 올바르게 로드하고 숨기고 숨긴 후 하위 구성 요소를 정의하지 않았습니다.

이것은 Angular Directive의 좋은 사용 사례입니다.이런 것은 의외로 유용하다.

@Directive({
  selector: '[removeAfter]'
})
export class RemoveAfter {
  constructor(readonly element: ElementRef<HTMLElement>) { }
 
  /**
   * Removes the attributed element after the specified number of milliseconds.
   */
  @Input() removeAfter: number;

  ngOnInit() {
    setTimeout(() => {
      this.element.nativeElement.remove();
    }, this.removeAfter);
  }
}

사용방법:

<div [removeAfter]="3000">Removed after 3 seconds</div>

TS 파일 내

showMyContainer: boolean = false;

HTML에서

<button (click)="showMyContainer=!showMyContainer">Show/Hide</button>

<div *ngIf="showMyContainer">
     your code
</div>

스택블릿 보기

누군가 도움을 받았다니 기쁘네요.

아래의 코드 스니펫을 사용하여 할 수 있습니다.

각도 코드:

 export class AppComponent {  
    toggleShowHide: string = "visible";  
 }

HTML 템플릿:

  Enter text to hide or show item in bellow: 
  <input type="text" [(ngModel)]="toggleShowHide">
  <br>
  Toggle Show/hide:
  <div [style.visibility]="toggleShowHide">   
     Final Release Angular 2!
  </div>

니즈에 따라서는*ngIf또는[ngClass]="{hide_element: item.hidden}"여기서 CSS 클래스hide_element{ display: none; }

*ngIf상태 변수를 변경할 경우 문제가 발생할 수 있습니다.*ngIf이 경우 CSS를 사용하여 삭제합니다.display: none;필수 항목입니다.

저는 위의 @inoabrian 솔루션이 효과가 있었습니다.페이지를 새로 고치고 숨겨진 요소가 페이지에 다시 나타나는 상황이 발생했습니다.제가 해결한 일은 이렇습니다.

export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;

ngOnInit() {
      if (condition is true) {
        this.showJoinTodayBtn = true;
      } else {
        this.showJoinTodayBtn = false;
      }
}

set Timeout 함수에 bind(이것)추가하면 동작을 시작합니다.

setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);

및 HTML 변경으로

<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

로.

<div *ngIf="edited" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

언급URL : https://stackoverflow.com/questions/35163009/angular-2-show-and-hide-an-element