无法使用@viewchild

时间:2018-11-22 13:25:56

标签: angular viewchild

我正在从事Angular-6项目。我已经在ngxbootstrap模态中创建了一个工作正常的表单。该表单具有各种输入元素,我想访问其中的几个元素,但是问题是,每当我尝试使用@viewchild访问这些元素时,结果都是不确定的,这主要是由于这些元素在DOM上不存在。因此,我可以通过下面的任何方式访问它们吗?

@Component({
selector: 'app-roles',
templateUrl: './roles.component.html',
styleUrls: ['./roles.component.scss'],
providers:[NgbActiveModal],
})
export class RolesComponent implements OnInit,AfterViewInit {
@ViewChild('dataTable') table:ElementRef;
@ViewChild('rolename') rolename:ElementRef; //Here it shows undefined
dataTable:any;
roleref:any;
error_array=new Array();
all_roles=new Array();
added:boolean;
closeResult: string;
modalRef: NgbModalRef;
is_shown:boolean;


profileForm=new FormGroup({
rolename:new FormControl('',[Validators.required,Validators.minLength(4)])
});
constructor(private roleservice:RolesService,private fb:FormBuilder,private 
 modalService: NgbModal,public activeModal: NgbActiveModal) 
{
}

ngOnInit() {
this.dataTable=$(this.table.nativeElement);
this.dataTable.dataTable();

}

ngAfterViewInit() {
}

open(content,form:NgForm) {
this.is_shown=true;
this.modalRef = this.modalService.open(content,{ 
size: "lg",
centered: false,
backdrop: 'static'});
this.modalRef.result.then((result) => {
  this.closeResult = `Closed with: ${result}`;
}, (reason) => {
    this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}

private getDismissReason(reason: any): string {
this.is_shown=false;
this.profileForm.reset();
if (reason === ModalDismissReasons.ESC) {
  return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
  return 'by clicking on a backdrop';
} else {
  return  `with: ${reason}`;
}
}
}

以下是HTML代码

  <ng-template #content let-d="dismiss">
                <form class="form" [formGroup]="profileForm" (ngSubmit)="onSubmit()" autocomplete="off" >
                <div class="modal-header">
                  <h4 class="modal-title">Add New Role</h4>
                  <button type="button" #clsbtn class="close" aria-label="Close" (click)="d('Cross click')">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>

        <div class="modal-body" *ngIf="is_shown==true">
            <div class="modal-body">
              <div class="col-md-5">
                                <div class="card-content">
                                    <div class="input-group">
                                        <span class="input-group-addon">
                                            <i class="material-icons">face</i>
                                        </span>
                                        <div class="form-group"><input type="text" #rolename formControlName="rolename"  class="form-control" placeholder="RoleName..." required/><span class="material-input"></span></div>
                                        <div *ngIf="profileForm.get('rolename').invalid &&  profileForm.get('rolename').touched" class="alert alert-danger">
                                            <div *ngIf="profileForm.get('rolename').errors.required">
                                                RoleName is required.
                                              </div>
                                              <div *ngIf="profileForm.get('rolename').errors.minlength">
                                                RoleName must be at least 4 characters long.
                                              </div>
                                        </div>
                                    </div>
                                 </div>
      </div>
                    </div>
                  </div>
                </div>
                <div class="modal-footer">
                  <!--<button type="button" class="btn btn-light" (click)="d('Close click')">Close</button>-->
                    <button class="btn btn-danger btn-round" style="position:relative;right:60px" [disabled]="profileForm.invalid">
                            <i class="material-icons">check</i> Add
                        </button>   
                </div>
                </form>
              </ng-template>

2 个答案:

答案 0 :(得分:0)

dataTable我认为没有在视图上定义。

rolename是在*ngIf内定义的,当条件为false时,您可能会尝试访问它。

您可以尝试这样的事情:

private yourElement: ElementRef;

@ViewChild('elementName') set elementName(content: ElementRef) {
  this.yourElement = content;
}

,并在组件中可用时使用yourElement

答案 1 :(得分:0)

这是不可能的,因为当您从ngxbootstrap调用open方法时,modalservice模态会将模板内容动态地附加到组件中。

ngOnInit或ngAfterViewInit不允许您检索嵌入元素的引用,因为您的元素未插入到DOM中。