2017-06-28 43 views
0

我想在Angular 4中動態構建一個導航欄,並同時理解Angular。如何使用* ngIf構建導航欄?

app.components.ts

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

export class newRoutes{ 
    route: string; 
} 
var NEWROUTES: newRoutes[]=[ 
    {route: "<li><a routerLink='/home' routerLinkActive='active' [routerLinkActiveOptions]=' {exact: true}'>Home</a></li>"}, 
    {route: "<li><a routerLink='/scan' routerLinkActive='active'>Order</a> </li>"}, 
    {route: "<li><a routerLink='/find' routerLinkActive='active'>Search</a></li>"}, 
    {route: "<li><a routerLink='/status' routerLinkActive='active'>Status</a></li>"} 
] 
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'] 
}) 
export class AppComponent { 
    title = 'Inspiredby'; 
    newroutes: newRoutes[] = NEWROUTES; 
} 

enter image description hereapp.component.html

<div style="text-align:center"> 
    <p>{{title}}</p> 
</div> 
<nav> 
    <ul> 
     <li *ngFor="let newroute of newroutes">{{newroute.route}}</li> 
    </ul> 
</nav> 
<router-outlet></router-outlet> 

請參閱圖像的結果。

我試過把* ngFor放在<ul><div>之間<ul></ul>標籤。

我認爲ngIf和ngFor在呈現之前應用於代碼。 PS我嘗試過使用谷歌搜索,並有一些解決方案,但他們不適合我的工作方式。

enter image description here

+1

有什麼問題呢?你所指的'* ngIf'在哪裏? – crash

回答

1

你的HTML應該是這樣的。你通過HTML,所以你需要綁定HTML

<div style="text-align:center"> 
    <p>{{title}}</p> 
</div> 
<nav> 
    <ul> 
     <li *ngFor="let newroute of newroutes"><span [innerHtml]="{{newroute.route}}"></span></li> 
    </ul> 
</nav> 
<router-outlet></router-outlet> 

變化陣列狀

var NEWROUTES: newRoutes[]=[ 
    {route: "<li><a [routerLink]="['/home']" routerLinkActive='active' [routerLinkActiveOptions]=' {exact: true}'>Home</a></li>"}, 
    {route: "<li><a [routerLink]="[/scan']" routerLinkActive='active'>Order</a> </li>"}, 
    {route: "<li><a [routerLink]="['/find']" routerLinkActive='active'>Search</a></li>"}, 
    {route: "<li><a [routerLink]="[/status']" routerLinkActive='active'>Status</a></li>"} 
] 
+0

導航欄現在顯示謝謝你,但它不再工作。我相信這是因爲角度已經剝離了我的一些HTML。警告導航到http:// localhost:4200/ 5platform-b​​rowser.es5.js:1017警告:清理HTML會剝離某些內容(請參閱http://g.co/ng/security#xss)。 –

+0

更新回答請參閱plaese –

+0

感謝您的嘗試,但這些更改導致了很多錯誤。 –