2017-06-04 35 views
0

我使用@angular/cli创建了一个新的角度应用程序。在那个应用程序模板已经有app component。在该应用程序组件内部,我想使用另一个component,它叫做user。所以在@Component里面有一个叫templateUrlproperty,也有人说只使用template。所以我应该使用哪一个,哪个最好。目前我正在尝试使用templateUrl如何在角度设置模板url 2

觉得这是我的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也没有工作。我很困惑。希望你对此有所帮助。

+0

如果你想使用的应用程序组件内部的用户组件,然后使用''应用的模板中。 – Santosh

+0

那么'templateUrl'为 –

+0

很多时候,最好有一个单独的模板文件,以便它更容易编辑和维护... U使用templateUrl提供文件链接...如果你想添加内嵌html ,然后使用模板 – Santosh

回答

0

使用我的用户组件与应用程序组件。 如果你想使用的用户组件与应用程序组件,然后

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

  • 添加所述用户组件内app.module

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

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

+0

我想用它作为'templateUrl' –

+0

'我不想' - >你不想使用templateurl?或者你想使用模板网址? – Santosh

+0

对不起,我的坏。用模板属性输入错误 –

0

与012无关,只需使用下面的我的app component中的选择器。

里面我的app.component.html我们应该使用user组件selector名称如下。

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

这将显示app component

3

名称selectoruser component内容在user.component.ts文件和文件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>`, 
}) 

如果要创建文件手动记得在app.module.ts文件declarations添加UserComponent

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

需要在.ts文件中添加html组件,但在templateUrl中,您可以提供html文件的链接,您可以在其中为html组件保留单独的文件。 –