I have the following component
@Component({
selector: 'app-models-sd-htmlview',
styleUrls: ['./sd.component.scss'],
template: `
<iframe id="htmlview" style="width:100%; height:200%;" [src]="iframe"></iframe>
`
})
export class HtmlViewComponent implements OnInit {
@Input() urlhash;
@Input() predictiontag;
public iframe;
constructor(public sanitizer: DomSanitizer)
{
this.sanitizer = sanitizer;
};
ngOnInit()
{
var url = "http://localhost:8080/htmlview/" this.urlhash "/" this.predictiontag ".html";
this.iframe = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
<app-models-sd-htmlview [urlhash]="urlhash" [predictiontag]="predictiontag"></app-models-sd-htmlview>
But when I render everything, this is what I see. The values for this.urlhash
and this.predictiontag
are undefined.
CodePudding user response:
For some reason, it takes time to get the values for 'urlhash' and/or 'predictiontag' in the parent, so them are not "binded" yet to the 'HtmlViewComponent' component when it execute ngOnInit() method.
Try this little change, to achive that 'iframe' property only try to gets its value when 'urlhash' and 'predictiontag' get their value:
export class HtmlViewComponent implements OnInit {
@Input()
set data (data : {
urlhash: string;
predictiontag: string;
}) {
var url = "http://localhost:8080/htmlview/" data.urlhash "/" data.predictiontag ".html";
this.iframe = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
...
ngOnInit() {}
...
And in your parent HTML:
<app-models-sd-htmlview [data]="{ urlhash: urlhash, predictiontag: predictiontag }">
</app-models-sd-htmlview>
NOTE: If it works fine, probably this shortened form will work as well:
<app-models-sd-htmlview [data]="{ urlhash, predictiontag }">
</app-models-sd-htmlview>
CodePudding user response:
A simple *ngIf
will prevent the component from instantiating while the variables are undefined.
<app-models-sd-htmlview *ngIf="urlhash && predictiontag" [urlhash]="urlhash" [predictiontag]="predictiontag">
That assumes that your two variables become defined at some point. If not, then the problem lies in the parent component.