繁体   English   中英

Angular-如何在组件模板中引用类变量?

[英]Angular - How to reference class variables in a component template?

我是Angular的新手,所以如果我在问题中使用一些错误/怪异的术语,请原谅我。

我有这个Angular组件,可以根据用户的输入来计算两个不同的URL。 现在,我想将计算出的URL注入相关的角度组件中,以便最终的HTML将产生具有以下行为的div:-在背景中加载静态图像(由url2引用); -单击时,将iframe(引用url1)作为主div的子元素动态添加

请参阅下面相应的TypeScript代码(经过简化以使其易于阅读):

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { Store } from '@ngrx/store';

@Component({
    selector: 'my-component-selector',
    template: `
        <table  width="100%">
            <tr>
                <td>
                    <div class="ng-scope embed-responsive embed-responsive-16by9">
                        <div class="embed-responsive-item" onclick="$('<iframe>',{src:'URL1 PLACEHOLDER',style:'border:0;width:100%;height:100%;',frameborder:0,allowfullscreen:true,scrolling:'no'}).appendTo(this);" style="background-image:url('URL2 PLACEHOLDER');background-size:contain;background-position:center center;background-repeat:no-repeat;cursor:pointer;"></div>
                    </div>
                </td>
            </tr>
        </table>
    `
})

export class MyComponent implements OnInit{

    url1;
    url2;

    constructor(private store: Store<State>, private sanitizer: DomSanitizer) {
        this.url1 = 'https://my.url.com/remote?param1=10&param2=20';
        this.url2 = 'https://my.url.com/remote?param1=30&param2=40';
    }

    ngOnInit() {
        this.url1 = 'https://my.url.com/remote?param1=10&param2=20';
        this.url2 = 'https://my.url.com/remote?param1=30&param2=40';
    }
}

如果我直接在Angular组件代码中编写两个url,则一切正常(请参阅URL1 PLACEHOLDER和URL2 PLACEHOLDER)。 但是,我正在努力尝试在相应的占位符中使用类变量“ url1”和“ url2”的内容。

我尝试使用“ this.url1”和“ this.url2”,{{url1}}和{{url2}},{{this.url1}}和{{this.url2}}以及其他一些选项,包括出价变量内容在iframe代码中使用“ [src]”之类的内容,但所有这些内容最终都会出错,或者变量名称本身会添加到生成的HTML代码中。

有人可以告诉我该如何做吗?

提前致谢!

而不是用jquery的方式来实现。 单击图像时,可以使用ngIf在Angular Way中轻松加载iframe。

https://stackblitz.com/edit/angular-2b4oqr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM