1# ComponentContent
2
3**ComponentContent** represents an entity encapsulation of component content, which can be created and transmitted outside of UI components. It allows you to encapsulate and decouple dialog box components. The underlying implementation of **ComponentContent** uses BuilderNode. For details, see [BuilderNode](js-apis-arkui-builderNode.md).
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> **ComponentContent** is not available in DevEco Studio Previewer.
10
11
12## Modules to Import
13
14```ts
15import { ComponentContent } from '@kit.ArkUI';
16```
17
18## ComponentContent
19
20### constructor
21
22constructor(uiContext: UIContext, builder: WrappedBuilder\<[]>)
23
24A constructor used to create a **ComponentContent** object.
25
26**Atomic service API**: This API can be used in atomic services since API version 12.
27
28**System capability**: SystemCapability.ArkUI.ArkUI.Full
29
30**Parameters**
31
32| Name   | Type                                     | Mandatory| Description                              |
33| --------- | ----------------------------------------- | ---- | ---------------------------------- |
34| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | Yes  | UI context required for creating the node.|
35| builder  | [WrappedBuilder\<[]>](../../quick-start/arkts-wrapBuilder.md) | Yes  |   **WrappedBuilder** object that encapsulates a builder function that has no parameters.|
36
37### constructor
38
39constructor(uiContext: UIContext, builder: WrappedBuilder\<[T]>, args: T)
40
41A constructor used to create a **ComponentContent** object.
42
43**Atomic service API**: This API can be used in atomic services since API version 12.
44
45**System capability**: SystemCapability.ArkUI.ArkUI.Full
46
47**Parameters**
48
49| Name   | Type                                     | Mandatory| Description                              |
50| --------- | ----------------------------------------- | ---- | ---------------------------------- |
51| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | Yes  | UI context required for creating the node.|
52| builder  | [WrappedBuilder\<[T]>](../../quick-start/arkts-wrapBuilder.md) | Yes  |   **WrappedBuilder** object that encapsulates a builder function that has parameters.|
53| args     |     T     |   Yes  |   Parameters of the builder function encapsulated in the **WrappedBuilder** object.|
54
55### constructor
56
57  constructor(uiContext: UIContext, builder: WrappedBuilder\<[T]>, args: T, options: BuildOptions)
58
59A constructor used to create a **ComponentContent** object.
60
61**Atomic service API**: This API can be used in atomic services since API version 12.
62
63**System capability**: SystemCapability.ArkUI.ArkUI.Full
64
65**Parameters**
66
67| Name   | Type                                     | Mandatory| Description                              |
68| --------- | ----------------------------------------- | ---- | ---------------------------------- |
69| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | Yes  | UI context required for creating the node.|
70| builder  | [WrappedBuilder\<[T]>](../../quick-start/arkts-wrapBuilder.md) | Yes  |   **WrappedBuilder** object that encapsulates a builder function that has parameters.|
71| args     |     T     |   Yes  |   Parameters of the builder function encapsulated in the **WrappedBuilder** object.|
72| options | [BuildOptions](./js-apis-arkui-builderNode.md#buildoptions12)                                                    | Yes  |  Build options, which determine whether to support the behavior of nesting **@Builder** within **@Builder**.                                        |
73
74**Example**
75``` ts
76import { ComponentContent, NodeContent, typeNode } from "@kit.ArkUI"
77
78interface ParamsInterface {
79  text: string;
80  func: Function;
81}
82
83@Builder
84function buildTextWithFunc(fun: Function) {
85  Text(fun())
86    .fontSize(50)
87    .fontWeight(FontWeight.Bold)
88    .margin({ bottom: 36 })
89}
90
91@Builder
92function buildText(params: ParamsInterface) {
93  Column() {
94    Text(params.text)
95      .fontSize(50)
96      .fontWeight(FontWeight.Bold)
97      .margin({ bottom: 36 })
98    buildTextWithFunc(params.func)
99  }
100}
101
102@Entry
103@Component
104struct Index {
105  @State message: string = "HELLO"
106  private content: NodeContent = new NodeContent();
107
108  build() {
109    Row() {
110      Column() {
111        Button('addComponentContent')
112          .onClick(() => {
113            let column = typeNode.createNode(this.getUIContext(), "Column");
114            column.initialize();
115            column.addComponentContent(new ComponentContent<ParamsInterface>(this.getUIContext(),
116              wrapBuilder<[ParamsInterface]>(buildText), {
117                text: this.message, func: () => {
118                  return "FUNCTION"
119                }
120              }, { nestingBuilderSupported: true }))
121            this.content.addFrameNode(column);
122          })
123        ContentSlot(this.content)
124      }
125      .id("column")
126      .width('100%')
127      .height('100%')
128    }
129    .height('100%')
130  }
131}
132
133```
134
135### update
136
137update(args: T): void
138
139Updates the parameters of the builder function encapsulated in the **WrappedBuilder** object. The parameter type must be the same as that passed in **constructor**.
140
141**Atomic service API**: This API can be used in atomic services since API version 12.
142
143**System capability**: SystemCapability.ArkUI.ArkUI.Full
144
145**Parameters**
146
147| Name| Type| Mandatory| Description                                                        |
148| ------ | ---- | ---- | ------------------------------------------------------------ |
149| args   | T    | Yes  | Parameters of the builder function encapsulated in the **WrappedBuilder** object. The parameter type must be the same as that passed in **constructor**.|
150
151**Example**
152
153```ts
154import { ComponentContent } from "@kit.ArkUI";
155
156class Params {
157  text: string = ""
158  constructor(text: string) {
159    this.text = text;
160  }
161}
162
163@Builder
164function buildText(params: Params) {
165  Column() {
166    Text(params.text)
167      .fontSize(50)
168      .fontWeight(FontWeight.Bold)
169      .margin({bottom: 36})
170  }.backgroundColor('#FFF0F0F0')
171}
172
173@Entry
174@Component
175struct Index {
176  @State message: string = "hello"
177
178  build() {
179    Row() {
180      Column() {
181        Button("click me")
182            .onClick(() => {
183                let uiContext = this.getUIContext();
184                let promptAction = uiContext.getPromptAction();
185                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
186                promptAction.openCustomDialog(contentNode);
187
188                setTimeout(() => {
189                  contentNode.update(new Params("new message"));
190                }, 2000);    // Automatically update the text in the dialog box after 2 seconds.
191            })
192      }
193      .width('100%')
194      .height('100%')
195    }
196    .height('100%')
197  }
198}
199```
200
201### reuse
202
203reuse(param?: Object): void
204
205Passes the reuse event to the custom component in this **ComponentContent** object.
206
207**Atomic service API**: This API can be used in atomic services since API version 12.
208
209**System capability**: SystemCapability.ArkUI.ArkUI.Full
210
211**Parameters**
212
213| Name| Type  | Mandatory| Description                                                                    |
214| ------ | ------ | ---- | ------------------------------------------------------------------------ |
215| param  | Object | No  | Parameters of the builder function encapsulated in the **WrappedBuilder** object. The parameter type must be the same as that passed in **constructor**.|
216
217### recycle
218
219recycle(): void
220
221Passes the recycle event to the custom component in this **ComponentContent** object.
222
223**Atomic service API**: This API can be used in atomic services since API version 12.
224
225**System capability**: SystemCapability.ArkUI.ArkUI.Full
226
227```ts
228import { ComponentContent } from '@kit.ArkUI';
229
230class Params {
231  text: string = ""
232
233  constructor(text: string) {
234    this.text = text;
235  }
236}
237
238@Builder
239function buildText(params: Params) {
240  ReusableChildComponent2({ text: params.text });
241}
242
243@Component
244struct ReusableChildComponent2 {
245  @Prop text: string = "false";
246
247  aboutToReuse(params: Record<string, object>) {
248    console.log("ReusableChildComponent2 Reusable " + JSON.stringify(params));
249  }
250
251  aboutToRecycle(): void {
252    console.log("ReusableChildComponent2 aboutToRecycle " + this.text);
253  }
254
255  build() {
256    Column() {
257      Text(this.text)
258        .fontSize(50)
259        .fontWeight(FontWeight.Bold)
260        .margin({ bottom: 36 })
261    }.backgroundColor('#FFF0F0F0')
262  }
263}
264
265@Entry
266@Component
267struct Index {
268  @State message: string = "hello"
269
270  build() {
271    Row() {
272      Column() {
273        Button("click me")
274          .onClick(() => {
275            let uiContext = this.getUIContext();
276            let promptAction = uiContext.getPromptAction();
277            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
278            promptAction.openCustomDialog(contentNode);
279
280            setTimeout(() => {
281              contentNode.reuse(new Params("new message"));
282              contentNode.recycle();
283            }, 2000); // Automatically update the text in the dialog box after 2 seconds.
284          })
285      }
286      .width('100%')
287      .height('100%')
288    }
289    .height('100%')
290  }
291}
292```
293
294### dispose
295
296dispose(): void
297
298Disposes of this **ComponentContent** object, which means to cancel the reference relationship between the **ComponentContent** object and its backend entity node.
299
300**Atomic service API**: This API can be used in atomic services since API version 12.
301
302**System capability**: SystemCapability.ArkUI.ArkUI.Full
303
304**Example**
305
306```ts
307import { BusinessError } from '@kit.BasicServicesKit';
308import { ComponentContent } from '@kit.ArkUI';
309
310class Params {
311  text: string = ""
312  constructor(text: string) {
313    this.text = text;
314  }
315}
316
317@Builder
318function buildText(params: Params) {
319  Column() {
320    Text(params.text)
321      .fontSize(50)
322      .fontWeight(FontWeight.Bold)
323      .margin({bottom: 36})
324  }.backgroundColor('#FFF0F0F0')
325}
326
327@Entry
328@Component
329struct Index {
330  @State message: string = "hello"
331
332  build() {
333    Row() {
334      Column() {
335        Button("click me")
336            .onClick(() => {
337                let uiContext = this.getUIContext();
338                let promptAction = uiContext.getPromptAction();
339                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
340                promptAction.openCustomDialog(contentNode);
341
342                setTimeout(() => {
343                  promptAction.closeCustomDialog(contentNode)
344                    .then(() => {
345                      console.info('customdialog closed.')
346                      if (contentNode !== null) {
347                        contentNode.dispose();   // Dispose of the contentNode object.
348                      }
349                    }).catch((error: BusinessError) => {
350                      let message = (error as BusinessError).message;
351                      let code = (error as BusinessError).code;
352                      console.error(`closeCustomDialog args error code is ${code}, message is ${message}`);
353                    })
354                }, 2000);     // Automatically close the dialog box after 2 seconds.
355            })
356      }
357      .width('100%')
358      .height('100%')
359    }
360    .height('100%')
361  }
362}
363```
364
365
366### updateConfiguration
367
368updateConfiguration(): void
369
370Updates the configuration of the entire node by passing in a [system environment change](../apis-ability-kit/js-apis-app-ability-configuration.md) event.
371
372**Atomic service API**: This API can be used in atomic services since API version 12.
373
374**System capability**: SystemCapability.ArkUI.ArkUI.Full
375
376> **NOTE**
377>
378> The **updateConfiguration** API is used to instruct an object to update itself. The update is based on the current changes in the system environment.
379
380**Example**
381```ts
382import { NodeController, FrameNode, ComponentContent, typeNode } from '@kit.ArkUI';
383import { AbilityConstant, Configuration, EnvironmentCallback } from '@kit.AbilityKit';
384
385@Builder
386function buildText() {
387  Column() {
388    Text('hello')
389      .width(50)
390      .height(50)
391      .fontColor($r(`app.color.text_color`))
392  }.backgroundColor($r(`app.color.start_window_background`))
393}
394
395const componentContentMap: Array<ComponentContent<[Object]>> = new Array();
396
397class MyNodeController extends NodeController {
398  private rootNode: FrameNode | null = null;
399
400  makeNode(uiContext: UIContext): FrameNode | null {
401    return this.rootNode;
402  }
403
404  createNode(context: UIContext) {
405    this.rootNode = new FrameNode(context);
406    let component = new ComponentContent<Object>(context, wrapBuilder(buildText));
407    componentContentMap.push(component);
408    this.rootNode.addComponentContent(component);
409  }
410
411  deleteNode() {
412    let node = componentContentMap.pop();
413    this.rootNode?.dispose();
414    node?.dispose();
415  }
416}
417
418function updateColorMode() {
419  componentContentMap.forEach((value, index) => {
420    value.updateConfiguration();
421  })
422}
423
424@Entry
425@Component
426struct FrameNodeTypeTest {
427  private myNodeController: MyNodeController = new MyNodeController();
428
429  aboutToAppear(): void {
430    let environmentCallback: EnvironmentCallback = {
431      onMemoryLevel: (level: AbilityConstant.MemoryLevel): void => {
432        console.log('onMemoryLevel');
433      },
434      onConfigurationUpdated: (config: Configuration): void => {
435        console.log('onConfigurationUpdated ' + JSON.stringify(config));
436        updateColorMode();
437      }
438    }
439    // Register a callback.
440    this.getUIContext().getHostContext()?.getApplicationContext().on('environment', environmentCallback);
441    this.myNodeController.createNode(this.getUIContext());
442  }
443
444  aboutToDisappear(): void {
445    // Remove the reference to the custom node from the map and release the node.
446    this.myNodeController.deleteNode();
447  }
448
449  build() {
450    Row() {
451      NodeContainer(this.myNodeController);
452    }
453  }
454}
455```
456