How can I call a specific method from the class decorator when some `* ngIf` condition is met?

How can I call a specific method from the class decorator when some *ngIf condition is *ngIf . I have a script similar to this AngularJS question which uses ng-init () but ng-init is not part of Angular2

 <div *ngIf="obj.someProperty" callSomeMethod() > <!--render inner parts--> </div> 
+6
source share
2 answers

It depends on what callSomeMethod() does, but one of them is to add a directive to the *ngIf element and execute this logic in the OnInit tag of this directive.

 <div *ngIf="obj.someProperty" some-method-directive> <!--render inner parts--> </div> 

And in another place:

 @Directive({ selector='[some-method-directive]', }) class SomeMethodDirective implements OnInit { // OnInit imported from angular2/core ngOnInit(){ // insert your someMethod lofic } } 

If you need access to the parent component in this method, you can get it through the constructor injection in the directive:

 constructor(@Host(ParentComponent) private parent: ParentComponent){ } 

and you will access it through this.parent .

This is the most similar approach that I can come up with for the ng1 approach, but, as I said, depending on what someMethod() needs to be done, this may not be an appropriate solution. If not, please comment / edit your question to explain why, and this will give me a better idea of ​​what we are doing here.

+2
source

You can use the custom directive ngIf and template :

 <template [ngCondition]="obj.someProperty" (show)="callSomeMethod()"> <h3 >if callback!</h3> </template> 

you should be able to add callbacks for true / false conditions (show / hide).

Directive Source:

 @Directive({ selector: '[ngCondition]' }) export class NgCondition { @Output('show') private show:EventEmitter<any> = new EventEmitter<any>(); @Output('hide') private hide:EventEmitter<any> = new EventEmitter<any>(); private _viewContainer:ViewContainerRef; private _templateRef:TemplateRef; private _prevCondition:any; constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef) { this._viewContainer = _viewContainer; this._templateRef = _templateRef; this._prevCondition = null; } @Input() public set ngCondition(newCondition:boolean) { if (newCondition && (isBlank(this._prevCondition) || !this._prevCondition)) { this._prevCondition = true; this._viewContainer.createEmbeddedView(this._templateRef); this.show.emit({}); } else if (!newCondition && (isBlank(this._prevCondition) || this._prevCondition)) { this._prevCondition = false; this._viewContainer.clear(); this.hide.emit({}); } } } 
+2
source

All Articles