Ralph
Ralph

Reputation: 569

What is wrong with the way I am passing this @Input in Angular?

I am trying to pass a model from one component to another in Angular 5.

I have a base page that hosts two other pages. The html looks like this:

<div [hidden]="!loading">
<page-one *ngIf="!showPageTwo"
             (model)="model"
             (next)="showPageTwo = true">
</page-one>
<page-two *ngIf="showPageTwo"
           [model]="model">
</page-two>

Page one looks like this:

import section....

@Component({
selector: 'page-one',
templateUrl: './pageOneComponent.html'
})
export class PageOneComponent {

public model: ExampleViewModel;
public otherModel: NotTheModelThatIsImportantHere;

@Output('next') onNextEmitter = new EventEmitter<void>();
@Output("model") modelEmitter = new EventEmitter<ExampleViewModel>();

contructor ....

onSubmit() {
    this.exampleService.doSomething(this.otherModel).then(response => {
        this.model = response;
        this.modelEmitter.emit(this.model);
        this.onNextEmitter.emit();                
    });
}

Page Two looks like this:

imports...

@Component({
selector: 'page-two',
templateUrl: './pageTwoComponent.html'
})

export class PageTwoComponent {
public copyOfModel: ExampleViewModel;

@Input() model: ExampleViewModel;

constructor() { }

ngOnInit() {
    this.copyOfModel = this.model; //this is undefined
}

Here is what is really confusing me. If I change the base page like so:

<page-one *ngIf="!showPageTwo"
         (model)="model = $event"
         (next)="showPageTwo = true">
</page-one>

And then change page one like this:

onSubmit() {
    this.exampleService.doSomething(this.otherModel).then(response => {
        this.modelEmitter.emit(response);
        this.onNextEmitter.emit();                
    });
}

Then the @Input value is not undefined. It is the model I was hoping to pass. So why am I unable to pass a property like this, but I can pass the server response? I am not understanding this.

Thanks.

Upvotes: 0

Views: 62

Answers (1)

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

This line doesn't do anything: (model)="model". You have to set the model to something (e.g. (model)="model = 1").

In your case you want it to be the value that was emitted from your this.modelEmitter.emit(response); line. In Angular, your emitted value is accessed in your template code for that output via the $event variable.

Putting this altogether you needed to set your template up as you now have it: (model)="model = $event".

Here is the Angular cookbook for component interaction around this topic: https://angular.io/guide/component-interaction#parent-listens-for-child-event

Upvotes: 2

Related Questions