输入变量未从模板中的@Input 属性 获取值。 Angular 5
Input variable not taking value from @Input property at template. Angular 5
我尝试了一些 angular 5 的 prime-ng 实验,我发现了一些困难(相对于 angular 5),我用下一个模板制作了一个组件:
<p>Chemi-tabla works! Y ahora un mensage de nuestros patrocinadores: {{this.nombre}}</p>
<p-dataTable [value]="_postsArray" [loading]="loading"
loadingIcon="fa-spinner" [rows]="10" [paginator]="true"
[multiSortMeta]="multiSortMeta" selectionMode="Single" [(selection)]="selectedUserInfo">
<p-header>Cabecera de la Chemi Tabla.</p-header>
<p-footer>Lo de abajo de la chemi tabla, vamos lo que va arrastrando.</p-footer>
<p-column selectionMode="single"></p-column>
<p-column field="userId" header="Usuario ID" sortable="true" [filter]="true" filterPlaceholder="Search"></p-column>
<p-column field="id" header="IDE" sortable="true" [filter]="true" [filter]="true" filterPlaceholder="Search"></p-column>
<p-column field="title" header="Título" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
<p-column field="body" header="Body" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
</p-dataTable>
但是行:
<p>Chemi-tabla works! And now a message: {{this.nombre}}</p>
未在 {{this.nombre}} 中打印任何内容,如果我调试组件中的代码,它的值是未定义的。
我的索引 html 是下一个:
<chemi-tabla [nombre]="Hello World">
Loading chemi's table </chemi-tabla>
component.ts 文件是下一个:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import {UserService} from './shared/user/user.service';
import {IPosts} from './shared/interfaces';
import {DataTableModule,SharedModule} from 'primeng/primeng';
import { HttpClientModule } from '@angular/common/http';
@Component({
selector: 'chemi-tabla',
templateUrl: './chemi-tabla.component.html',
providers: [UserService],
styleUrls: ['./chemi-tabla.component.css']
})
export class ChemiTablaComponent implements OnInit {
_postsArray: IPosts[];
msgs : CustomMessage[];
selectedUserInfo : IPosts;
@Input() nombre: string;
constructor(private apiSerivce: UserService) {
console.log("Constructor chemi tabla component.");
}
getPosts(): void {
this.apiSerivce.getPosts()
.subscribe(
resultArray => this._postsArray = resultArray,
error => console.log('Error :: ' + error)
)
}
ngOnInit(): void {
console.log(this.nombre);
this.getPosts();
}
}
class CustomMessage{
severity:string;
summary:string;
detail:string;
constructor(private severity_a: string, private summary_a: string, detail_a:string) {
this.severity = severity_a;
this.summary = summary_a;
this.detail = detail_a;
}
}
最后这是 module.ts 我正在使用的:
import { HttpModule } from '@angular/http';//para promesas subscribe y demás
import { BrowserModule } from '@angular/platform-browser';//necesariko para pintar en pantalla
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';//necesario para redirecciones*1
import {UserService} from './shared/user/user.service';//servicio que me trae datos
import {IPosts} from './shared/interfaces';//tipos de datos
import {MessageService} from 'primeng/components/common/messageservice';//no se usa
import {DataTableModule,SharedModule} from 'primeng/primeng';//necesaroi para la tabla
import { ChemiTablaComponent } from './chemi-tabla.component';//mi componente
export const ROUTES: Routes = [
{ path: '', component: ChemiTablaComponent }//*1 podríamos decirle a un modulo que en tal direccion vaya a tal componente....
];
@NgModule({
declarations: [ ChemiTablaComponent ],
imports: [
BrowserModule,
CommonModule,
DataTableModule,
SharedModule,
RouterModule.forChild(ROUTES),
HttpModule
],
providers: [ UserService ],
bootstrap: [ ChemiTablaComponent ]
})
export class ChemisModule {
public nombre : string;
}
一切都在编译并且 p-datatable 工作正常但我无法使 {{nombre}} 变量出现我遗漏了一些东西并且我敢打赌这是一个非常愚蠢的问题,但我看不出它是什么。
您的代码存在三处错误。
- 您无法从您的模板中使用
this
访问您的变量。
在你的标记中,你应该只写 {{nombre}}
- 您的
ChemisModule
中不需要 public nombre : string;
- 此外,如果你想通过你的道具传递一个对象,你应该按照
<chemi-tabla [nombre]="'Hello World'">
或 <chemi-tabla nombre="Hello World">
如果你使用方括号 []
,你必须把一个对象在引号之间。
编辑
此外,我刚刚意识到您正试图将一个属性传递给您的自举组件。检查这个
正如 link 中所述,您不能将 Input
传递给您的根组件。您可能也不需要这样做。您可以在根组件中定义它。
我的朋友 "Bunyamin Coskuner" 就在我之前回答说问题是我的组件被引导了。
他在上面链接的问题给出了解决方案
我在 component.ts 文件上使用了这个构造函数:
import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
....
constructor(private apiSerivce: UserService, private elementRef:ElementRef) {
console.log("Constructor chemi tabla component.");
let nombreAttribute = this.elementRef.nativeElement.getAttribute('nombre');
this.nombre = nombreAttribute;
console.log(this.nombre);
}
现在可以正常使用了。我正在解释我必须在我的问题 post 中的代码中进行的必要更改。
我必须使用 ElementRef 模块(来自@angular/core)来获取属性值 'nombre',就像这样:this.elementRef.nativeElement.getAttribute('nombre'); 从我们传递给构造函数的自我引用 "constructor(private apiSerivce: UserService, private elementRef:ElementRef)" 这样我就可以正确地获取属性值。
据我了解,这是因为它是引导模块,仍然需要了解更多相关信息,但这就是我今天需要的解决方案。
所以请在我之上投票给 Bunyamin Coskuner,他是摇滚的人
我尝试了一些 angular 5 的 prime-ng 实验,我发现了一些困难(相对于 angular 5),我用下一个模板制作了一个组件:
<p>Chemi-tabla works! Y ahora un mensage de nuestros patrocinadores: {{this.nombre}}</p>
<p-dataTable [value]="_postsArray" [loading]="loading"
loadingIcon="fa-spinner" [rows]="10" [paginator]="true"
[multiSortMeta]="multiSortMeta" selectionMode="Single" [(selection)]="selectedUserInfo">
<p-header>Cabecera de la Chemi Tabla.</p-header>
<p-footer>Lo de abajo de la chemi tabla, vamos lo que va arrastrando.</p-footer>
<p-column selectionMode="single"></p-column>
<p-column field="userId" header="Usuario ID" sortable="true" [filter]="true" filterPlaceholder="Search"></p-column>
<p-column field="id" header="IDE" sortable="true" [filter]="true" [filter]="true" filterPlaceholder="Search"></p-column>
<p-column field="title" header="Título" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
<p-column field="body" header="Body" sortable="true" [filter]="true" filterMatchMode="contains"></p-column>
</p-dataTable>
但是行:
<p>Chemi-tabla works! And now a message: {{this.nombre}}</p>
未在 {{this.nombre}} 中打印任何内容,如果我调试组件中的代码,它的值是未定义的。
我的索引 html 是下一个:
<chemi-tabla [nombre]="Hello World">
Loading chemi's table </chemi-tabla>
component.ts 文件是下一个:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import {UserService} from './shared/user/user.service';
import {IPosts} from './shared/interfaces';
import {DataTableModule,SharedModule} from 'primeng/primeng';
import { HttpClientModule } from '@angular/common/http';
@Component({
selector: 'chemi-tabla',
templateUrl: './chemi-tabla.component.html',
providers: [UserService],
styleUrls: ['./chemi-tabla.component.css']
})
export class ChemiTablaComponent implements OnInit {
_postsArray: IPosts[];
msgs : CustomMessage[];
selectedUserInfo : IPosts;
@Input() nombre: string;
constructor(private apiSerivce: UserService) {
console.log("Constructor chemi tabla component.");
}
getPosts(): void {
this.apiSerivce.getPosts()
.subscribe(
resultArray => this._postsArray = resultArray,
error => console.log('Error :: ' + error)
)
}
ngOnInit(): void {
console.log(this.nombre);
this.getPosts();
}
}
class CustomMessage{
severity:string;
summary:string;
detail:string;
constructor(private severity_a: string, private summary_a: string, detail_a:string) {
this.severity = severity_a;
this.summary = summary_a;
this.detail = detail_a;
}
}
最后这是 module.ts 我正在使用的:
import { HttpModule } from '@angular/http';//para promesas subscribe y demás
import { BrowserModule } from '@angular/platform-browser';//necesariko para pintar en pantalla
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';//necesario para redirecciones*1
import {UserService} from './shared/user/user.service';//servicio que me trae datos
import {IPosts} from './shared/interfaces';//tipos de datos
import {MessageService} from 'primeng/components/common/messageservice';//no se usa
import {DataTableModule,SharedModule} from 'primeng/primeng';//necesaroi para la tabla
import { ChemiTablaComponent } from './chemi-tabla.component';//mi componente
export const ROUTES: Routes = [
{ path: '', component: ChemiTablaComponent }//*1 podríamos decirle a un modulo que en tal direccion vaya a tal componente....
];
@NgModule({
declarations: [ ChemiTablaComponent ],
imports: [
BrowserModule,
CommonModule,
DataTableModule,
SharedModule,
RouterModule.forChild(ROUTES),
HttpModule
],
providers: [ UserService ],
bootstrap: [ ChemiTablaComponent ]
})
export class ChemisModule {
public nombre : string;
}
一切都在编译并且 p-datatable 工作正常但我无法使 {{nombre}} 变量出现我遗漏了一些东西并且我敢打赌这是一个非常愚蠢的问题,但我看不出它是什么。
您的代码存在三处错误。
- 您无法从您的模板中使用
this
访问您的变量。 在你的标记中,你应该只写{{nombre}}
- 您的
ChemisModule
中不需要 - 此外,如果你想通过你的道具传递一个对象,你应该按照
<chemi-tabla [nombre]="'Hello World'">
或<chemi-tabla nombre="Hello World">
如果你使用方括号[]
,你必须把一个对象在引号之间。
public nombre : string;
编辑
此外,我刚刚意识到您正试图将一个属性传递给您的自举组件。检查这个
正如 link 中所述,您不能将 Input
传递给您的根组件。您可能也不需要这样做。您可以在根组件中定义它。
我的朋友 "Bunyamin Coskuner" 就在我之前回答说问题是我的组件被引导了。 他在上面链接的问题给出了解决方案 我在 component.ts 文件上使用了这个构造函数:
import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
....
constructor(private apiSerivce: UserService, private elementRef:ElementRef) {
console.log("Constructor chemi tabla component.");
let nombreAttribute = this.elementRef.nativeElement.getAttribute('nombre');
this.nombre = nombreAttribute;
console.log(this.nombre);
}
现在可以正常使用了。我正在解释我必须在我的问题 post 中的代码中进行的必要更改。
我必须使用 ElementRef 模块(来自@angular/core)来获取属性值 'nombre',就像这样:this.elementRef.nativeElement.getAttribute('nombre'); 从我们传递给构造函数的自我引用 "constructor(private apiSerivce: UserService, private elementRef:ElementRef)" 这样我就可以正确地获取属性值。
据我了解,这是因为它是引导模块,仍然需要了解更多相关信息,但这就是我今天需要的解决方案。
所以请在我之上投票给 Bunyamin Coskuner,他是摇滚的人