Can a component delete its own template and return it conditionally?

I am looking at the source code *ngIf:

@Input()
  set ngIf(condition: any) {
    if (condition && !this._hasView) {
      this._hasView = true;
      this._viewContainer.createEmbeddedView(this._template);
    } else if (!condition && this._hasView) {
      this._hasView = false;
      this._viewContainer.clear();
    }
  }

Can I have a component that I like as below?

@Component({})
class MyComponent{

     constructor ( 
              public _template : TemplateRef,
              public _viewContainer : ViewContainerRef) {
    }

   onSomeButtonClick(condition){
       if(condition){
          removeMyView();
       }else{
          putTheViewBackIfItsRemoved();
        }
   }
}

Trying to use logic ngIfinside a component does not work, which I think because viewContainerRef for the component is empty

EDIT:

Just to mention that I don't want to hide the view, I just want to remove it from the DOM.

In other words, can we be something like ngIfhost elements? I know that you cannot place the directive on host, so I thought that perhaps with ViewContainerand TemplateRefyou can achieve the same.

, , Angular , ViewContainerRef DOM; , Angular ?

, - , ?

, Angular ( ), , , ngIf :

, ngIf :

:

 <div *ngIf="condition"></div>

, , , , , div, , , .

ngIf.


:

:

, ngIf :

@Component({

  host:{
    '*ngIf':'shouldBeRemoved'
  }
})
class MyComponent{

, ngIf , , , viewContainerRef - .

, , ngIf ngIf , , .

.

+4
4

, . , . ngIf, ngIf template , , , .

+4

:

@Component({
    selector: 'your-selector',
    template: '<template [ngIf]="showView"> Here is my component template </template> ',
})
class MyComponent{

    showView: boolean = true;

   onSomeButtonClick(condition){
       if (condition) {
          this.showView = false;
       } else {
          this.showView = true;
        }
   }
}

onClick, onSomeButtonClick ,

+5

, angular2 typescript.

.

typescript , . .

, .. .

, ( ), , , / angular2.

, javascript, , . , angular2 .

, , , . .

( , , .)

+1

I suggest that the component that you want it to remove itself is unmounted by its host with a boolean value associated with ngIf. in order for the component to practically delete itself, the logical value must have a state value in Redux, and this state will be set only by the component for which you want it to be deleted by itself :)

0
source

Source: https://habr.com/ru/post/1672657/


All Articles