Est*_*ask 31 angularjs typescript angular
如何将属性从包装器组件透明地转换为嵌套组件?
考虑到有
const FIRST_PARTY_OWN_INPUTS = [...];
const FIRST_PARTY_PASSTHROUGH_INPUTS = ['all', 'attrs', 'are', 'passed'];
@Component({
selector: 'first-party',
inputs: [...FIRST_PARTY_OWN_INPUTS, ...FIRST_PARTY_PASSTHROUGH_INPUTS],
template: `
<div>
<third-party [all]="all" [attrs]="attrs" [are]="are" [passed]="passed"></third-party>
<first-party-extra></first-party-extra>
</div>
`,
directives: [ThirdParty]
})
export class FirstParty { ... }
Run Code Online (Sandbox Code Playgroud)
输入是否可以批量翻译,因此它们不会在模板中枚举?
上面的代码应该重新创建Angular 1.x指令的配方:
app.directive('firstParty', function (thirdPartyDirective) {
const OWN_ATTRS = [...];
const PASSTHROUGH_ATTRS = Object.keys(thirdPartyDirective[0].scope);
return {
scope: ...,
template: `
<div>
<third-party></third-party>
<first-party-extra></first-party-extra>
</div>
`,
compile: function (element, attrs) {
const nestedElement = element.find('third-party');
for (let [normalizedAttr, attr] of Object.entries(attrs.$attr)) {
if (PASSTHROUGH_ATTRS.includes(normalizedAttr)) {
nestedElement.attr(attr, normalizedAttr);
}
}
},
...
};
});
Run Code Online (Sandbox Code Playgroud)
const FIRST_PARTY_OWN_INPUTS = ['not', 'passthrough'];
const FIRST_PARTY_PASSTHROUGH_INPUTS = ['all', 'attrs', 'are', 'passed'];
const generateAttributes(arr) {
return arr.map(att => '[' + att + '] = "' + att + '"').join(' ');
}
//-------------------------------------------------------//////////////////
import {Component} from '@angular/core'
@Component({
selector: 'third-party',
inputs: [...FIRST_PARTY_PASSTHROUGH_INPUTS],
template: `
<div>
{{all}} , {{attrs}} , {{are}} , {{passed}}
</div>
`
})
export class ThirdParty {
}
@Component({
selector: 'first-party',
inputs: [...FIRST_PARTY_OWN_INPUTS, ...FIRST_PARTY_PASSTHROUGH_INPUTS],
template: `
<div>
<div>
{{not}} , {{passthrough}}
</div>
<third-party ${generateAttributes(FIRST_PARTY_PASSTHROUGH_INPUTS)}></third-party>
<first-party-extra></first-party-extra>
</div>
`,
directives: [ThirdParty]
})
export class FirstParty {
}
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Hello {{name}}</h2>
<first-party [not]="'not'" [passthrough]="'passthrough'"
[all]="'all'" [attrs]="'attrs'" [are]="'are'" [passed]="'passed'">
</first-party>
</div>
`,
directives: [FirstParty]
})
export class App {
constructor() {
this.name = 'Angular2 (Release Candidate!)'
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :)
归档时间: |
|
查看次数: |
3504 次 |
最近记录: |