我有app.component,post-create.component和post-list.component。app.component.html看起来像这样:app.component.html
<app-header></app-header>
<main>
<app-post-create (postCreated)="onAddedPost($event)" ></app-post-create>
<app-post-list [posts]="storedPosts" ></app-post-list>
</main>
post-list.component.ts看起来像这样post-list.component.ts
import { Component, Input } from '@angular/core';
import { Post } from '../post'
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent {
@Input() posts:Post[] = [];
}
post-create.component.ts看起来像这样post-create.component.ts
import { sharedStylesheetJitUrl } from '@angular/compiler';
import { Component, EventEmitter, Injectable, Output, OutputDecorator } from '@angular/core';
import { Post } from '../post'
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent {
enteredContent='';
enteredTitle='';
@Output() postCreated: EventEmitter<Post> = new EventEmitter<Post>();
onAddPost(){
const post={title:this.enteredTitle,content:this.enteredContent};
this.postCreated.emit(post);
}
}
而app.component.ts看起来像这样app.component.ts
import { Component, Output,Input } from '@angular/core';
import { Post } from '../app/posts/post';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
storedPosts: Post[] = [];
onAddedPost(post:Post){
this.storedPosts.push(post);
}
}
问题是,当我按下添加后,它不会显示新的职位。有什么想法吗?编辑:我的post.create.component.html看起来也像这样post.create.component.html
<mat-card>
<mat-form-field>
<input matInput type="text" [(ngModel)]="enteredTitle">
</mat-form-field>
<mat-form-field>
<textarea matInput rows="6" [(ngModel)]="enteredContent"></textarea>
</mat-form-field>
<button mat-raised-button
(click)="onAddPost()">Save post!</button>
</mat-card>
post-list.component.html看起来像这样:
<mat-accordion multi="true" *ngIf="posts.length>0" >
<mat-expansion-panel *ngFor="let post of posts">
<mat-expansion-panel-header>
{{post.title}}
</mat-expansion-panel-header>
{{post.content}}
</mat-expansion-panel>
</mat-accordion>
<p class="mat-body-1" *ngIf="posts.length <=0">no posts added yet</p>
3条答案
按热度按时间643ylb081#
Angular的
@Input
只会在底层引用被调整的情况下识别其变量的更改。由于Array#push
不会影响它的持有变量,因此它们可能不会被检测到。可以使用spread syntax来添加新元素,而不是Array#push
。尝试以下操作
使用
ngOnChanges()
钩子检查@Input
的变化您可以使用
ngOnChanges
钩子检查是否在子组件中检测到更改。尝试以下操作我修改了你的Stackblitz。
alen0pnh2#
我认为这与更改检测有关,数组是引用类型,因此您必须更改数组在内存中的存储位置,以确保更改检测能够运行。
oaxa6hgo3#
试试看
public void onDestination(){
}
而不是
public void run(){
}