简体   繁体   中英

How do I pass a JSON array to an Angular2 template with @Input from a ASP.NET MVC View?

I'm new to Angular2 and have many questions.

I have some controllers that I wrote in AngularJS that I now want to convert to Angular2 components.

I would like to pass JSON data to the component and use in the template. In AngularJS I used ng-init to do this.

I have tried initialising the component in the ASP.NET MVC view with:

<review [reviewJson]="@Newtonsoft.Json.JsonConvert.SerializeObject(Model.CustomerReviews)"></review>

The component looks like this:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'review',
    template: `
        <div id="reviews-wrapper" class="row">
            <div class="item col-sm-4 col-xs-6" *ngFor="let review of reviewJson">
                <div class="review-card">
                    <div class="review-image"><img [src]="review.Image"/></div>
                    <div class="review-name">review.Name</div>
                    <div class="review-text">review.Text</div>
                </div>
            </div>
        </div>
    `,
    providers: []
})

export class ReviewComponent implements OnInit {

    @Input() reviewJson: any;  

    constructor() {
    }

    ngOnInit() {
        console.log(this.reviewJson);
    }
}

The app.module file where I declare the review component looks like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

import { ReviewComponent } from './review.component';

@NgModule({
    imports: [
        BrowserModule,
        HttpModule
    ],
    declarations: [
        ReviewComponent
    ],
    bootstrap: [ReviewComponent],
    providers: [
    ]
})
export class AppModule { }

The console.log(this.reviewJson) is showing undefined when I load the page so obviously I'm doing something completely wrong.

Any help appreciated.

You cannot directly bind the MVC models into the angular template - fetch the data as JSON using service and then bind the value to it's @Input decorator

Hope this helps - happy coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM