【问题标题】:How to do Angular2 work with templates?Angular2如何使用模板?
【发布时间】:2017-10-22 03:39:09
【问题描述】:

我正在尝试将模板与 Angular2 一起使用,但它没有按预期工作。这是我到目前为止所尝试的。有没有人有任何想法或其他方法可以解决它?

首先,我使用的是 MEAN 堆栈,它 express 生成 index.html,nodejs 创建模板,angular 是应用程序。

index.html

{includes header.tpl}
<scripts> ... </scripts>
<my-app> Loading AppComponent content here ...</my-app>
{includes footer.tpl}

在我的 header.tpl 中,我有一些指令,我希望 Angular 应用程序解释它们

header.tpl

<html> 
   <header> ... </header>
   <body>
       <div *ngIf='user.status === "new" '> ADDED THIS </div>
   ...

app.component.ts

import { Component, Inject } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    moduleId: module.id,
    selector: 'my-app',
    template: `<h1>Hello</h1> <div *ngIf='user.status === "new"'> ADDED THIS 2 </div>`,
})

export class AppComponent {

     public user:any = {};

     constructor(@Inject(ActivatedRoute) public activatedRoute: ActivatedRoute) {
          this.checkParams();
     }

    private checkParams() {
        this.activatedRoute.queryParams.subscribe((params: Params) => {
            if (!!params['status'] && params['status'] === 'new') {
                this.user.status = 'new';
                console.log('I am new');
            } else {
                console.log('I am NOT new');
                this.user.status = 'old';
            }
            console.log('user', this.user);
        });
    }
}

当我通过

访问我的应用程序时

domain.com?status=new

只显示“已添加 2”,但我也想显示“已添加”。如您所见,“ADDED THIS 2”在 &lt;my-app&gt; 内部运行,“ADDED THIS”在外部运行。

所以有什么想法吗?谢谢。

【问题讨论】:

    标签: angular templates angular2-routing mean-stack angular2-directives


    【解决方案1】:

    这很简单,这是行不通的。您的标头代码不在 my-app 标签内,因此 Angular 当然不会接受它。

    您希望 Angular 呈现的所有内容都需要位于应用的根标签内或应用的组件中。

    【讨论】:

    • 嗨@Maarten Tibau,这个选项已经过测试,也没有工作。
    • 是的,但在my-app 标签内我也认为它不起作用,因为Angular 不使用模板引擎或任何东西。也许你可以用一些 Webpack 插件来解决它,也许是这样的? html-tpl-loader
    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2016-08-08
    • 1970-01-01
    • 2017-11-11
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多