5

i have a interface in angular4

interface StatusDetail {
    statusName: string,
    name: string
}

and i have assigned some values to it like

//angular Component

     export class EditComponent implements OnInit{
         statusDetail: StatusDetail;
         ngOnInit() {
           this.statusDetail.statusName = 'text Status';
           this.statusDetail.name= 'text Name';
         }
     }  

i'm trying to reset to default null like this

         SetNull() { 
           this.statusDetail = null
         }

but it gives error

Type null is not assignable to type StatusDetail

how can i do this?

4 Answers 4

8

You need to declare statusDetail as StatusDetail | null:

export class EditComponent implements OnInit{
     statusDetail: StatusDetail | null;
     ngOnInit() {
       this.statusDetail.statusName = 'text Status';
       this.statusDetail.name= 'text Name';
     }
 }  
Sign up to request clarification or add additional context in comments.

7 Comments

What's the point of having the interface then? Would it not make more sense to define a default StatusDetail with empty fields?
i can,t do this because every time i tried to access its values it give error of being null value
@bugs: I agree, this would be better.
@Faisal: Well, that's the nature of null. Not sure what you are trying to achieve here? Why are you setting it to null? Also, see bugs comment.
i have a condition on html <div statusDetail != null">Status is Not Null</div> i want to hide this via this condition
|
5

You can reset/initiate your interface like below.

this.statusDetail = <StatusDetail>{};

Now the object will have the default value. You can set to undefined too, why null btw ? Why not

this.statusDetail = undefined ;

Comments

1

Given that you defined the interface with those properties, it does not make too much sense to assign null to your object.

If you are trying to reset your default values, why don't you set them as empty?

SetNull() { 
  this.statusDetail = {
    statusName: '',
    name: ''
  }
}

If you want to check this condition in the HTML, you can create a new private method specifically for that:

isStatusDetailDefined(): boolean {
  return this.statusDetail.statusName && this.statusDetail.name
}

and

*ngIf="isStatusDetailDefined()"

2 Comments

but this condition will never get false ngIf !="statusDetail != null"
Because the condition doesn't make sense, given the interface. See the modified answer
0

If you want to set null to interface value, you set {} as any

setNull(){
 this.statusDetail= {} as any
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.