我有html
<input name="name" [(ngModel)]="address.name" matInput >
和我的ts
一样
public address: Address;
...
ngOnInit() {
this.service.getAddress(1).subscribe(address => {
this.address = address;
});
}
我的界面看起来像
export interface Address {
...
name: string;
}
当我尝试填充输入时,出现错误:
TypeError:无法读取未定义的属性“名称”
我知道发生这种情况是因为address
对象为null,直到在subscribe方法中填充它为止。如何摆脱这个错误?
答案 0 :(得分:1)
按以下步骤初始化为空对象,
public address = new Address();
或在模板(脏)中使用* ngIf
<input name="name" *ngIf="address" [(ngModel)]="address.name" matInput >
是
export class Address {...}
答案 1 :(得分:0)
如果要考虑这一点,请尝试使用public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
Fragment Frag = new Fragment();
Fragment FragmentA;
Fragment FragmentB;
Fragment FragmentC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this); // mOnNavigationItemSelectedListener
FragmentA = new FragmentA();
FragmentB = new FragmentB();
FragmentC = new FragmentC();
if (savedInstanceState != null)
{
Frag = getSupportFragmentManager().getFragment(savedInstanceState, "Frag");
}
else
loadFragment(FragmentA);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment = null;
int i = menuItem.getItemId();
if (i == R.id.fragmentA) {
fragment = FragmentA;
} else if (i == R.id.fragmentB) {
fragment = FragmentB;
} else if (i == R.id.fragmentC) {
fragment = FragmentC;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment)
{
if (fragment != null)
{
getSupportFragmentManager().beginTransaction().hide(FragmentA).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
getSupportFragmentManager().beginTransaction().show(fragment).commit();
Frag = fragment;
return true;
}
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Frag", Frag);
}
}
作为可选类型,然后将any
分配给{}
:
address