所以我有这个代码:
这是templateUrl:
<button class="btn btn-success" (click)="showNewPop()" >New</button>{{shownew}}
<app-new-pop *ngIf="shownew" (close)="closeNewPop($event)"></app-new-pop>
这是Component.ts
private shownew = false;
private myBooksArr:Book[];
constructor(private bookService:BookService) {
this.myBooksArr = Array<Book>();
}
ngOnInit() {
this.getBooks();
}
showNewPop(){
this.shownew = true;
}
closeNewPop(newBook:Book){
this.shownew = false;
if (newBook) {
this.myBooksArr.splice(0, 0, newBook);
}
}
private getBooks(){
this.bookService.getBooks().subscribe(data=>{
data.items.forEach(element => {
this.myBooksArr.push(new Book(element.id,
element.volumeInfo.authors,
element.volumeInfo.publishedDate,
element.volumeInfo.title));
});
});
}
现在的问题是,当myBooksArr数组为空时 showew变为true,但* ngIf不显示app-new-pop组件
我不知道为什么
这是删除书功能(如果有帮助的话)
showDeletePop(i:number) {
this.currnetBook = this.myBooksArr[i];
this.currnetBook.indedx = i;
this.showDelete = true;
}
closeDeleetePop(mydelete:boolean){
this.showDelete = false;
if(mydelete){
this.myBooksArr.splice(this.currnetBook.indedx,1);
}
}
更新!
发现了一个黑客,如果有兴趣的人可以使用。 就是这样:
private flag:boolean= false;
showNewPop(){
console.log(this.myBooksArr.length);
if(this.myBooksArr.length==0){
this.myBooksArr.push(new Book("",[""],"0",""))
this.flag =true;
}
this.shownew = true;
}
closeNewPop(newBook:Book){
this.shownew = false;
if(newBook && !this.flag){
this.myBooksArr.splice(0, 0, newBook);
}
if(newBook && this.flag){
this.myBooksArr.splice(0,1,newBook);
this.flag = false;
}
}
我仍然想知道为什么它为什么一开始不起作用
如果您知道那会很酷
答案 0 :(得分:1)
尝试将* ngIf放在div中。
<div *ngIf="shownew">
<app-new-pop (close)="closeNewPop($event)"></app-new-pop>
</div>
在ngIf的引用中:https://angular.io/api/common/NgIf
@Component({
selector: 'ng-if-simple',
template: `
<button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
show = {{show}}
<br>
<div *ngIf="show">Text to show</div>
`
})
class NgIfSimple {
show: boolean = true;
}
答案 1 :(得分:0)
您不是在}
之前误读了ngOnInit
吗?
constructor(private bookService:BookService) {
this.myBooksArr = Array<Book>();
}
ngOnInit() {
this.getBooks();
}