如何在Angular自定义元素中从index.html接收数组类型@Input参数
问题根源
- Angular的方括号绑定语法
[]仅在Angular项目内部的模板文件中生效,你直接写在index.html原生HTML中时,浏览器不会识别该语法,对应传值无法被Angular解析,所以productId接收到的是undefined。 - 命名不匹配+自定义元素属性规则问题:
- 原生HTML属性不区分大小写,Angular的驼峰命名
@Input参数会自动映射为短横线分隔的小写HTML属性,比如@Input() productId对应的HTML属性为product-id,@Input() userId对应的HTML属性为user-id - 你当前组件内的
@Input参数写的是全小写的userid、productid,和标签上的命名完全不匹配,就算绑定逻辑正常也无法拿到对应值。
- 原生HTML属性不区分大小写,Angular的驼峰命名
- 直接写
productId="['101','B102']"属于原生HTML的字符串属性传值,拿到的自然是字符串类型,原生HTML本身不支持直接传递数组、对象等复杂类型。
解决方案
第一步:先修正组件@Input命名
export class TestComponent implements OnInit { // 驼峰命名,对应HTML中的user-id属性 @Input() userId = ''; // 驼峰命名,对应HTML中的product-id属性 @Input() productId: any[]; }
第二步:选择任意一种方式传递数组
方案1:字符串传值+组件内自动解析(推荐,使用简单)
把index.html中的参数改成标准JSON格式字符串传值,组件内接收时自动转成数组:
index.html写法:
<test-reco user-id="I8763" product-id='["101","B102"]'></test-reco>
组件内修改接收逻辑:
export class TestComponent implements OnInit { @Input() userId = ''; private _productId: any[] = []; @Input() set productId(val: string | any[]) { if (typeof val === 'string') { try { this._productId = JSON.parse(val); } catch (err) { this._productId = []; } } else { this._productId = val || []; } } get productId() { return this._productId; } }
方案2:JS手动赋值(适合传递复杂动态值)
如果需要传递动态更新的数组、对象等复杂类型,可以通过DOM属性直接赋值:
index.html写法:
<test-reco id="testReco" user-id="I8763"></test-reco> <script> const recoElement = document.querySelector('#testReco'); // 直接给DOM元素属性赋值数组,Angular会直接识别为@Input传入值 recoElement.productId = ['101', 'B102']; </script>
内容的提问来源于stack exchange,提问作者Ritesh Singh
相关产品推荐
相关产品推荐

