2

Requirement

I need to put dynamically created components in a container having rows and columns. Number of rows and columns depends on user input. Each component created at first takes 1x1, means 1 rows and 1 columns then it can be resized based on user requirement. Newly created component, first fill the row, if row is filled then it can be placed in the next row on leftmost column. so the story goes on until it fills the container as shown in the image:

enter image description here

Problem

The problem is that I cannot insert these components in the right alignment as expected to do that. What happens? If I add a first component and resize to 2x2, then adds another component of 1x1 and then 3rd of 1x1. This 3rd component assumed to be inserted below the 2nd component of 1x1 but it is being inserted below the first component of 2x2:

enter image description here

I hope now you are much more clear about what I want to do.

This problem can be solved if I wrap the newly created component in a new column. In a nut-shell, one column for one component. but don't know how to create column with each newly created component.

0

1 Answer 1

9

Get the Component's Reference i.e. ComponentRef and then get the HTMLElement <HTMLElement>componentRef.location.nativeElement. Now you are ready to change the styles...**

constructor(private CFR: ComponentFactoryResolver) {
}

private addComponent() {
    let componentFactory = this.CFR.resolveComponentFactory(MyComponent);

    // getting the component's reference
    let componentRef: ComponentRef<MyComponent> = this.location.container.createComponent(componentFactory);

    // getting the component's HTML
    let element: HTMLElement = <HTMLElement>componentRef.location.nativeElement;

    // adding styles
    element.classList.add('col-8 float-left');
    element.style.height = "100px";        
    element.style.width= "50px";
}

after adding all this, in browser developer tool when you run the app, you'll see something like this

<my-component class="col-8 float-left"></my-component>
Sign up to request clarification or add additional context in comments.

1 Comment

has anyone tried this code? i got an error. However the code is correct if you do element.classList.add('col-8'); and element.classList.add('float-left'); instead. I used angular 12

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.