【问题标题】:how to set the template url in angular 2如何在角度2中设置模板网址
【发布时间】:2017-11-05 10:54:33
【问题描述】:

我使用 @angular/cli 创建了一个新的 Angular 应用程序。在那个应用程序模板中已经有app component。在该应用程序组件中,我想使用另一个名为usercomponent。所以在@Component 里面有一个property,叫做templateUrl,也有人说只使用template。所以我应该使用哪个,哪个是最好的。目前我正在尝试使用templateUrl

认为这是我的app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

这是我的user.component.ts

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})

那么我如何将我的user 组件与app component 一起使用。我试过给relative paths,但它没有用,给absolute path也没有用。我糊涂了。希望您对此有所帮助。

【问题讨论】:

  • 如果你想在app组件中使用用户组件,那么在app的模板中使用<app-user></app-user>
  • 那么templateUrl 是为了什么
  • 很多时候最好有一个单独的模板文件,这样更容易编辑和维护...U使用templateUrl提供文件链接...如果你想添加内联html ,然后使用模板

标签: angular components angular-components


【解决方案1】:

将我的用户组件与应用组件一起使用。 如果你想将用户组件与应用组件一起使用,那么

  • 在app模板内添加用户组件 所以你的 app.template。 html 将包含 <app-user></app-user>

  • 在 app.module 中添加用户组件

@NgModule({ ... 声明:[AppComponent, UserComponent] ... })

您可以了解更多关于多个组件here

【讨论】:

  • 我想用templateUrl
  • I wan't -> 你不想使用templateurl?或者你想使用模板网址?
  • 对不起我的错。输入错误
【解决方案2】:

template url 无关,只需使用我的app component 中的选择器,如下所示。

在我的app.component.html 中,我们应该使用user 组件selector 名称,如下所示。

<div class="row">
    <app-user></app-user>
</div>

这将显示app component 中的user component 内容

【讨论】:

    【解决方案3】:

    在您的user.component.ts 文件中命名selector,并在app.component.ts 文件中的template 中使用它。然后你可以同时使用这两个组件。

    user.component.ts

    @Component({
      selector: 'app-user',
      templateUrl: './user.component.html', 
    })
    

    app.component.ts

    @Component({
      selector: 'app-root',
      template:`<app-user></app-user>`,
    })
    

    如果您手动创建文件,请记住在 declarationsapp.module.ts 文件中添加 UserComponent

    @NgModule({
      declarations: [
        AppComponent,
        UserComponent
      ],
    

    【讨论】:

    • 使用模板属性,您需要在 .ts 文件中添加 html 组件,但在 templateUrl 中,您可以提供 html 文件的链接,您可以在其中为 html 组件保留单独的文件。
    猜你喜欢
    • 2016-02-28
    • 2016-03-15
    • 2016-09-26
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2017-03-05
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多