如果使用带有then/else语法的模板,如何将ngFor循环中的当前变量传递给ngIf?
看起来它们在内联时使用时很好,但是无法从模板访问,例如:
<ul *ngFor="let number of numbers">
<ng-container *ngIf="number % 2 == 0; then even_tpl; else odd_tpl"><>/ng-container>
</ul>
<ng-template #odd_tpl>
<li>Odd: {{number}}</li>
</ng-template>
<ng-template #even_tpl>
<li>Even: {{number}}</li>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
模板似乎根本没有访问权限number,但如果内联使用它可以工作.
以下链接中的工作版和非工作版的完整示例:plunkr
我正在编写一个将对象或数组作为参数的函数,我想为其创建一个新的空副本,并使用原始对象中的转换数据填充它。
我想知道是否有一种方法可以简单地制作此新对象/数组,而不必测试事物的类型并采取适当的措施。
目前,“长距离”方法是:
const transf = (thing) => {
if (typeof(thing) === 'array') {
const new = []
} else {
const new = {}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有一种不错的“内置”方式可以执行以下操作:
const transf = (thing) => {
const new = thing.emptyCopy()
}
Run Code Online (Sandbox Code Playgroud)
我已经看过了,Object.create但是它总是使一个object(即使prototype是是array),并typeof返回一个字符串,该字符串不能与eg new等一起使用。
有没有捷径可以做到这一点,或者我不走运吗?
用户输入宠物名称,如果在字典中找到,代码返回宠物的价格,否则要求用户尝试不同的名称。想知道这是否可以用更少的代码行以更简洁的方式完成?
pets = {'bird': 3.5, 'cat': 5.0, 'dog': 7.25, 'gerbil': 1.5}
while True:
req_pet = input("Enter pet name: ")
if req_pet in pets:
for (pet, price) in pets.items():
if pet == req_pet:
print(price)
exit(0)
else:
print("Pet not found, let's try a different one?")
Run Code Online (Sandbox Code Playgroud)