我正在尝试使用Input装饰器传递json值,但是它不起作用。 我试图将数据父组件传递给子组件,但无法正常工作。
子组件
<div class="card">
<div class="card-body">
<h4 class="card-title">{{ analyticsTitle }}</h4>
<div *ngFor="let data of datas">
<a href="{{data.redirectionUrl}}" class="card-link">{{data.description}}</a>
</div>
<div class="text-right view-more">
<a href="{{viewMoreUrl}}">
{{ viewMore }}
</a></div>
</div>
</div>
TS
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-widget',
templateUrl: './widget.component.html',
styleUrls: ['./widget.component.scss']
})
export class WidgetComponent implements OnInit {
@Input('joke') datas=[];
ngOnInit() {
}
}
父组件
<app-widget *ngFor="let j of analytics" [joke]="j"></app-widget>
TS
import { Component, OnInit } from '@angular/core';
import { HomeService } from "./../../service/home.service";
@Component({
selector: 'app-bi-analytics-platform',
templateUrl: './bi-analytics-platform.component.html',
styleUrls: ['./bi-analytics-platform.component.scss']
})
export class BiAnalyticsPlatformComponent implements OnInit {
analytics = [];
analyticsTitle = '';
viewMore = '';
viewMoreUrl = '';
constructor(private homeService: HomeService) {
}
ngOnInit() {
this.homeService.homeDataWidget().subscribe(response => {
let res = response[0];
let heading = res['BI-Analytics'][0]['heading'][0];
this.analytics = res['BI-Analytics'][0]['body'];
this.analyticsTitle = heading['title'];
this.viewMore = heading['viewmore'];
this.viewMoreUrl = heading['viewmoreURL'];
});
}
}
JSON 1
[
{
"BI-Analytics": [{
"heading": [{
"viewmore": "View More",
"viewmoreURL": "http://google.com"
}],
"body": [{
"description": "test",
"redirectionUrl": "lik"
}]
}]
}]
JSON 2
[
{
"Test": [{
"heading": [{
"viewmore": "View More",
"viewmoreURL": "http://google.com"
}],
"body": [{
"description": "test",
"redirectionUrl": "lik"
}]
}]
}]
JSON 3-具有嵌套的json格式
[
{
"Test1": [{
"heading": [{
"viewmore": "View More",
"viewmoreURL": "http://google.com"
}],
"body": [{
"description": "test",
"redirectionUrl": "lik"
}]
},
{
"Test2": [{
"heading": [{
"viewmore": "View More",
"viewmoreURL": "http://google.com"
}],
"body": [{
"description": "test",
"redirectionUrl": "lik"
}]
}]
{
"Test3": [{
"heading": [{
"viewmore": "View More",
"viewmoreURL": "http://google.com"
}],
"body": [{
"description": "test",
"redirectionUrl": "lik"
}]
}]
}]
上面提到的格式,需要通过。所以我想传递如下值:
@Input() test1:
@Input() test2
建议这样做。
答案 0 :(得分:1)
看不到任何问题,但以防万一,请尝试以下操作:
<ng-container *ngFor="let j of analytics">
<app-widget [joke]="j"></app-widget>
</ng-container>
答案 1 :(得分:0)
您一次仅将一个Analytics(分析的单个对象)实例传递给Child组件,因此,它是一个传递而不是数组的对象。
console log of input parameter
解决方案:从父级内容中删除for循环: