I've been trying to define a variable with bracket notation just to get familiar with how it works and aren't getting any results. Unfortunatelt I'm on on a tablet with a keyboard using Plunkr so I can't open the console and see what's going wrong, hopefully someone can spot the problem without needing an error message from the console.
my code inside the component class currently looks like this
var demoA:string='name';
var demoB:string='city';
var demoD:string='';
var demoC:{[propName: string]:string}= {};
demoC['demoA']= demoD;
seing that I'm using typescript I didn't originally have var
at the beginning of the variables but I eventually decided to set it up as it was on the MDN site and still didn't get any results, the widget just stays stck on loading. I also tried adding this.
to everything in the attempt to create the new property. My goal is to have demoC
with a property of name=''
inside of it. What am I missing here?
Here's my entire file on plunker
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<p>{{demoA}}</p>
<p>{{demoB}}</p>
<br />
<p>{{demoC}}</p>
`,
})
export class App {
name:string;
var demoA:string='name';
var demoB:string='city';
var demoD:string='';
var demoC:{[propName: string]:string}= {};
demoC[demoA]= demoD;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
You have used the string
with name demoA
, not the variables value. It will create a property with name demoA
. Remove the ''
from the []
notation to let the []
syntax to evaluate the expression and get the value from it.
demoC[demoA]= demoD;
This is the example in TypeScript playground
According to your Plunker code, you have some errors
Remove the var
parts from the variables declarations. Put the assignment operator of the demoC
into your constructor
. It understands your statement as a duplicate variable.
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<p>{{demoA}}</p>
<p>{{demoB}}</p>
<br />
<p>{{demoC}}</p>
`,
})
export class App {
name: string;
demoA: string = 'name';
demoB: string = 'city';
demoD: string = '';
demoC: { [propName: string]: string} = {};
constructor() {
this.name = `Angular! v${VERSION.full}`;
this.demoC[this.demoA]= this.demoD;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Code example
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加