我试图显示一个我试图实现为模态的弹出窗口,但出现错误:
TypeError: Cannot read property 'open' of undefined
我将弹出窗口创建为组件:
import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import User from '../types/user'
@Component({
selector: 'app-modal',
templateUrl: './chat-user-profile.component.html',
styleUrls: ['./chat-user-profile.component.css']
})
export class ChatUserProfileComponent {
me: User;
ngOnInit() {}
@ViewChild('ChatUserProfile') modal: ElementRef;
open() {
this.modal.nativeElement.style.display = 'block';
}
close() {
this.modal.nativeElement.style.display = 'none';
}
}
<div #myChatUserProfile class="container">
<div class="content">
<p>Some content here...</p>
<div class="text-center mb-2">
<h4><span class="badge badge-pill">{{me?.username}}</span></h4>
</div>
<!-- <button (click)="save()">Save</button> -->
<button (click)="close()">Close</button>
</div>
</div>
现在我尝试通过单击按钮打开它
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: []
})
export class NavComponent {
isLoggedIn = false;
constructor(private amplifyService: AmplifyService, public router: Router) {
this.amplifyService.authStateChange$.subscribe(authState => {
const isLoggedIn = authState.state === 'signedIn' || authState.state === 'confirmSignIn';
if (this.isLoggedIn && !isLoggedIn) {
router.navigate(['']);
} else if (!this.isLoggedIn && isLoggedIn) {
router.navigate(['/chat']);
}
this.isLoggedIn = isLoggedIn;
});
}
public signOut() {
this.amplifyService.auth().signOut();
}
//Stuff for Profile Button
@ViewChild('app-modal') modal: ChatUserProfileComponent
openModal() {
this.modal.open();
}
}
<nav class="navbar navbar-toggleable-md navbar-inverse navbar-dark bg-dark fixed-top">
<a class="navbar-brand text-white" routerLink='/'>
<img src="../../assets/img/chat.png" width="30" height="30" class="d-inline-block align-top" alt="http://freepngimg.com/png/11489-chat-free-download-png">
<strong>ChatQL</strong>
</a>
<!--STUFF TO INTEGRATE THE POP UP-->
<app-modal #modal></app-modal>
<button (click)="openModal()">Open Modal</button>
<!------------->
<ul class="nav navbar-nav">
<li *ngIf="isLoggedIn" class="nav-item">
<button class="btn btn-primary" (click)="signOut()">Sign Out <i class="ion-log-in" data-pack="default" data-tags="sign in"></i></button>
</li>
</ul>
</nav>
我也尝试将模态添加到构造函数中,但这给了我一个 No Provider 错误。
我基于 chatQL 项目并使用 this 作为弹出窗口的模板。我认为初始化时出了点问题,但我不知道具体在哪里。
答案 0 :(得分:0)
在您的 HTML 代码中,您使用了模板引用 #modal
<app-modal #modal></app-modal>
因此在打字稿文件中,您必须将 '@ViewChild('app-modal')' 替换为 '@ViewChild('modal')',如下所示 >
@ViewChild('modal') modal: ChatUserProfileComponent
目前,您使用了错误的模板引用,因此您收到此未定义错误,因为没有引用 'app-modal' 的模板。