有一个changable templateUrl

时间:2017-02-28 13:58:07

标签: javascript angular typescript nativescript

我想知道是否可以让templateUrl取决于ifelse

import { Component } from "@angular/core";

@Component({
  selector: "grote-kerk",
  templateUrl: "pages/home/home.html"
})
export class AppComponent {
  // Your TypeScript logic goes here
}

1 个答案:

答案 0 :(得分:1)

除了评论中提供的建议外,您还可以创建自己的结构指令,并根据条件加载/卸载不同的布局。 例如,请查看此示例,其中contion正在检查设备是iOS还是Android,并根据操作系统加载不同的布局:

import { Component, Directive, ViewContainerRef, TemplateRef, Inject } from "@angular/core";
import { Device, platformNames } from "platform";
import { DEVICE } from "nativescript-angular/platform-providers";

@Directive({ selector: "[sdkIfAndroid]" })
export class IfAndroidDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.android) {
            container.createEmbeddedView(templateRef);
        }
    }
}

@Directive({ selector: "[sdkIfIos]" })
export class IfIosDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.ios) {
            container.createEmbeddedView(templateRef);
        }
    }
}

@Component({
    moduleId: module.id,
    templateUrl: "./create-custom-directive.component.html",
})
export class CreateCustomDirectiveExampleComponent {
}

使用该指令的HTML部分:

<GridLayout *sdkIfAndroid width="300" height="300" backgroundColor="#a4c639"></GridLayout>
<GridLayout *sdkIfIos width="300" height="300" backgroundColor="#0099CC"></GridLayout>

可以找到完整示例here